Wednesday, September 8, 2010

Data Binding Directions in WPF

Hello All,
As you all know that binding in WPF is simple with the help of "Binding" keyword we can bind the Item to any data source. For binding there must be 2 thing "Source" & "Target", The target can be any any Control or Property derived from DependencyProperty and the Source can be any of the following

  • Public Property of a control
  • CLR(Common Language Runtime) Object
  • XML Element
  • A Dataset
  • and the Static Resource
Text="{Binding ElementName=lbSource}"

Here I am going to discuss the various data binding direction available in the WPF. There are 4 different kind of binding Direction are available we can use them according to our need the various binding directions are.

  1. OneWay
  2. OneWayToSource
  3. OneTime
  4. TwoWay
OneWay :- The most common and the first direction used in the WPF data binding is OneWay. this is the default binding direction which does not need to be specified, in this direction the data always flow from Source to target. The TEXT property of the textblock default binding is OneWay. This is useful when we just want to display the result to the users.

OneWayToSource :- This is also similar to the OneWay binding but the main difference between them is , when we use the OneWayToSource direction the data flows from Target to Source. This can be useful when we want that a user can change the value in the back end.

OneTime :- OneTime property is also similar to the OneWay binding direction, but the thing is that using this option the change in the source not always reflect to the target, the target get updated only when the application load or there is a context change. This is pretty useful when we want to display a user a ReadOnly type of value which does not get change each time.

TwoWay :- This is the useful binding direction in the WPF, when we want that the value can be changed from either side. Here the changes get reflected each time a source value is changed or the target value is changed. This can be quite useful when we want to display the value to the user as well as allow user to change the the value in the back end.

Hope you all have understood waht all are the data binding direction in the WPF, as I always says thing are not complex until we know them. Here are examples for using the binding.

<TextBlock Width="248" Height="24" Text="Colors:"
<ListBox x:Name="lbSource" Width="248" Height="56">
<ListBoxItem Content="Blue"/>
<ListBoxItem Content="Green"/>
<ListBoxItem Content="Yellow"/>

<TextBlock Width="100" Height="30" Text="You selected color:" />

<TextBlock Width="100" Height="30">
<Binding ElementName="lbSource" Path="SelectedItem.Content"/>

I hope this post will help in understanding the things of bindings in WPF. Please feel free to post the comments.

Anil Kumar Pandey
MVP (Visual c#)