Wednesday, April 09, 2008

Databinding in WPF

Data binding in .Net has previouslybeen done by providing a data source and calling DataBind(). It has been a one way data flow initialized directly by user code. In WPF they have changed it a bit. To enable automatic synchronization they have basically implemented the Observer pattern. To make this happen they have implemented the properties in the UI component as DependencyProperties. A DependencyProperty is a static object on the class containing the property. The ordinary properties on the class are wrappers setting the value on the DependencyProperty. In this way you can subscribe to changes on the property through the DependencyProperty.

In the illustration I'm trying to show two connected textboxes. When typing the name of a font in the first TextBox, the font of the second should change accordingly.

This event driven synchronization is dependent on the fact that your object inherits DependencyObject and that your properties use DependencyProperties. If you want your UI to be data bound to something that is not a UI component, you can implement the INotifyPropertyChanged interface and fire the PropertyChanged event when your object changes.

The way to publish data to the UI could be to bind all the fields in the UI in relation to a parent container (the windows or something) and then set DataContext to the data object. This way your UI is filled with data very smoothly.

No comments:

Post a Comment