WPF Data Binding: Bind a generic object on a WPF designer

In Visual Studio 2010 Beta1, we have enabled data binding experience for a few data sources on WPF designer. Generic object or business object is one of them. Besides this, we have also supported multiple object selection in data source configuration wizard. I will show you all of the above features by walking through one example. In this example, I want to create a master-details form on a WPF designer by binding to the generic objects.

First, let’s create two classes called Customer and Order. And we establish one-to-many relationship between Customer and Order. This step is pretty similar to what needs to be done on a Winform designer.

image

Second, let’s add these two generic objects to data sources window. As I mentioned above, we now support selecting multiple objects in data source configuration wizard simultaneously.

image

 

After the addition, this is what displays in data sources window.

image

Third, let’s drag-drop from data sources window to the WPF designer to create a master-details form. We can bind any system or user controls to a particular data node. Here are the helps on “Customize Control Binding Dialog Box” and “How to: Add Custom Controls to the Data Sources Window”. In this example, I bind ListBox to the node Customer.LastName and DataGrid to the node Customer.Orders in the data sources window, and drag-drop these nodes to the WPF designer respectively.

Last, we need to fill the data to the form. In the third step, when we drag-drop the data nodes to the form, XAML code was automatically generated. That XMAL code is very similar to the one if we bind data to ADO.NET Entity Data Model. You can find detailed explanation about XAML code part in MilindLele’s post “WPF Data Binding: Creating a Master-Details form in Visual Studio 2010”. For the code behind the form, we set the data to the source property of the CollectionViewSource of the Customer object in the window loaded event handler.

 List<Customer> customers = new List<Customer>(); 
customers.Add(...);

System.Windows.Data.CollectionViewSource customerViewSource = 
  ((System.Windows.Data.CollectionViewSource)(this.FindResource("customerViewSource"))); 
customerViewSource.Source = customers;

Now press F5, we should be able to see the form loaded with the data.

image

As the master-details association is already created in XAML, different sets of orders will be displayed according to the selection of customer names.

Technorati Tags: WPF,Business Object,Generic Object,VS2010 Beta1