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}"
- OneWay
- OneWayToSource
- OneTime
- TwoWay
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.
<StackPanel>
<TextBlock Width="248" Height="24" Text="Colors:"
TextWrapping="Wrap"/>
<ListBox x:Name="lbSource" Width="248" Height="56">
<ListBoxItem Content="Blue"/>
<ListBoxItem Content="Green"/>
<ListBoxItem Content="Yellow"/>
</ListBox>
<TextBlock Width="100" Height="30" Text="You selected color:" />
<TextBlock Width="100" Height="30">
<TextBlock.Text>
<Binding ElementName="lbSource" Path="SelectedItem.Content"/>
</TextBlock.Text>
</TextBlock>
</StackPanel>
<TextBlock Width="248" Height="24" Text="Colors:"
TextWrapping="Wrap"/>
<ListBox x:Name="lbSource" Width="248" Height="56">
<ListBoxItem Content="Blue"/>
<ListBoxItem Content="Green"/>
<ListBoxItem Content="Yellow"/>
</ListBox>
<TextBlock Width="100" Height="30" Text="You selected color:" />
<TextBlock Width="100" Height="30">
<TextBlock.Text>
<Binding ElementName="lbSource" Path="SelectedItem.Content"/>
</TextBlock.Text>
</TextBlock>
</StackPanel>
I hope this post will help in understanding the things of bindings in WPF. Please feel free to post the comments.
Thanks
Anil Kumar Pandey
MVP (Visual c#)
Good article for beginners.
ReplyDeleteThanks Samantha... I will come up with some more details on it.
ReplyDeletekeep reading!!!!