WPF data binding

This article was originally published in VSJ, which is now part of Developer Fusion.
Microsoft’s Windows Presentation Foundation provides the platform for building applications and high fidelity experiences in Windows Vista, blending together application UI, documents, and media content. WPF contains two data sources for XML and Objects. To enhance productivity and include WPF applications in line of business, you need to employ best practices and guidelines on how to reuse existing internal frameworks through WPF data binding capabilities. Doing this will enable enterprises to benefit from advanced accessibility, data driven UI and highly stylized data visualization inherent to the WPF platform.

By leveraging what you already have taken numerous hours to create and maintain, you are ensuring an overall cost saving to your software development. WPF provides two data sources inherently: XmlDataSource and ObjectDataSource. The only problem is that there are many WPF data binding examples available, but most show how to bind to XML files. This is not always a realistic scenario, so you will be learning how to use your own custom business objects.

To demonstrate how to employ the tips included here, I’ll use the WPF reference application we built at Infragistics. Tangerine v1.0 is a WPF-based asset browser application. It has a pluggable architecture so that you can provide any number of different back-end asset providers while reusing the same snazzy UI that is based on the NetAdvantage for WPF toolset. In our first release, we have supplied an Amazon Web Services’ E-Commerce Service provider so that you can use the application to browse and search the Amazon.com catalogue (see Figure 1).

Figure 1
Figure 1: The Tangerine asset browser, displaying information from amazon.com

The goal of the application is to provide the .NET Community with another resource to learn how to implement a full WPF application, along with some guidance in integrating it into your existing enterprise framework (which is also included in the Tangerine download.)

Data Binding At a Glance

The idea behind data binding is to provide a mechanism for synchronization between two objects. In WPF, you are able to set up the binding as one-way, two-way, or one-way to source. The following code shows how to create a binding on the Content property of a Label to the Count property on the collection named Items.
<Label x:Name="NumberOfItems"
	Content="{Binding
	Source={StaticResource Items},
	Path=Count}" />
Matched with dependency properties (another new feature of WPF), which has a set of plumbing built-in for change notifications, the UI will automatically update its content based on update triggers in the data binding process. (You can also use objects that implement the System.ComponentModel.INotifyPropertyChanged interface to receive the same behaviour.)

I must just add a plug for one of my all-time favourite features in the data binding framework – the ability to use type converters. Converters have so many uses and are beyond the scope of this article; however, we have plenty of examples in the project and some useful converters for you to try out.

Setting Up an Intermediate Layer

Most of the time your enterprise framework, which includes your data layer libraries, will be compiled against the .NET Framework 2.0. This is okay and is still accessible since you may have other applications using this framework such as an ASP.NET website. However, some of the types that you will need to use are included beginning in .NET Framework 3.0. For this reason, I usually create a custom data provider in the presentation layer to use internally and handle the functions that are needed to convert the .NET 2.0-returned types into .NET 3.0. The AssetDataProvider class that is defined in the Tangerine WPF project represents this custom data provider. The purpose for this is to be an intermediate layer between the presentation and data layers. This is also an easy way to contain all of the functionality you will need when you want to declare an ObjectDataSource in XAML.
public class AssetBrowserProvider :
	System.Windows.DependencyObject
{
// Other Code...
	#region SearchResultsData
	private ObservableCollection<Asset>
		SearchResultsData;
	public ObservableCollection<Asset>
		SearchResultsData
	{
		get
		{
			if (_SearchResultsData == null)
			{
				_SearchResultsData = new
					ObservableCollection<Asset>();
			}
			return _SearchResultsData;
		}
		set
		{
			_SearchResultsData = value;
		}
	}
	#endregion
	private static void
		LoadCollectionHelper<T>(
		IList<T> source,
		IList<T> target,
		bool clearCollection
		) where T : EnterpriseObject
	{
		if (clearCollection)
		{
			Try
		// Other Code...
}
You can also notice that we have included a helper function that helps convert an IList collection from your data layer into another collection type, for example, an ObservableCollection (see Figure 2).

Figure 2
Figure 2: Class diagram of asset class

ObservableCollection

You might have noticed that we used a new collection type called ObservableCollection. This collection type was introduced in the .NET Framework 3.0, and really comes in handy with in WPF applications because any time the collection is updated, the UI gets a notification and renders itself with the new data as needed.

One might have chosen just to use ObservableCollection’s where needed in the enterprise framework. The problem with this is that all of your other applications become dependent upon .NET 3.0, which is not necessarily what you want since you may have other smart-client applications (e.g. ASP.NET web sites etc.) using this framework. However, if .NET 3.0+ is required for all of your applications that will use the enterprise framework, there is nothing wrong with just using this collection type.

Setting up the ObjectDataSource

This is easy:
<Window
	xml:lang="en-US"
	xmlns="http://schemas.microsoft.com/
		winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/
		winfx/2006/xaml"
	xmlns:local=
		"clr-namespace:LiberMagnus.
		AssetBrowser.Presentation"
		x:Class=
		"LiberMagnus.AssetBrowser.
		Presentation.Main"
	x:Name="MainWindow">
	<Window.Resources>
<!-- Other XAML Definitions for
	Your UI -->
<Window />
Anytime you need to update the contents, simply update your collection in the code-behind.

Binding

Finally, we are at the point we have been working toward: binding to your custom business objects. In this case we are using the ItemsSource property on the xamCarouselListBox and binding it to the ObservableCollection<Asset> property named SearchResultsData.
ItemsSource="{Binding Path=
	SearchResultsData,
	Mode=Default,
	Source={StaticResource
	AssetsDataProvider}}"
That is all there is to it. Anytime you need to update the contents, simply update your collection in the code-behind.

Data Binding in Microsoft Expression Blend

Alternatively, for an even easier experience to set up the binding (other than editing the XAML by hand), you can take advantage of the awesome abilities of Microsoft Expression Blend to set up the data binding for you. If you look on the Properties window in Blend for an object (see Figure 3), you can tell which properties you have data-bound, which is indicated by an orange box.

Figure 3
Figure 3: Property window in Blend

To change the binding (or set up a new one), you click the small orange square next to the property and choose “Data Binding…” from the context menu (see Figure 4). This displays the Data Binding Setup dialog where you can choose from your available data sources (which we can see the AssetsDataProvider).

Figure 4
Figure 4: Property context menu in Blend

In the fields tree you can also see all of the fields declared in the data source. This view only show matching types by default for the particular property you are binding to (see Figure 5).

(If you really want to set advanced options click the expand icon underneath the “Custom path expression” text box.)

Figure 5
Figure 5: Data binding setup dialog in Blend

Conclusion

We have taken some time reviewing what is needed to ensure that you can reuse your existing frameworks inside of a WPF application, and you are able to create an intermediate layer to facilitate calling your underlying data layer. We have also reviewed the new reference application available for WPF named Tangerine.


Ed Blankenship is the WPF and Windows Forms Technical Evangelist at Infragistics Inc., and is responsible for building reference applications and educating the community on various Microsoft technologies and Infragistics products. He is also a leader of the New Jersey .NET Users Group. You can read Ed Blankenship’s blog.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The trouble with programmers is that you can never tell what a programmer is doing until it's too late.” - Seymour Cray