DataBinding in WPF
Introduction
WPF provides a simple and powerful way to auto-update data between the business model and the user interface. This mechanism is called DataBinding.
Everytime when the data of your business model changes, it automatically reflects the updates to the user interface and vice versa. This is the preferred method in WPF to bring data to the user interface.
Databinding can be unidirectional (source -> target or target <- source), or bidirectional (source <-> target).
The source of a databinding can be a normal .NET property or a DependencyProperty. The target property of the binding must be a DependencyProperty.
To make the databinding properly work, both sides of a binding must provide a change notification that tells the binding when to update the target value.
On normal .NET properties this is done by raising the PropertyChanged event of the INotifyPropertyChanged interface. On DependencyProperties it is done by the PropertyChanged callback of the property metadata
Databinding is typically done in XAML by using the {Binding} markup extension. The following example shows a simple binding between the text of a TextBox and a Label that reflects the typed value:
<StackPanel>
<TextBox x:Name="txtInput" />
<Label Content="{Binding Text, ElementName=txtInput,
UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
DataContext
Every WPF control derived from FrameworkElement has a DataContext property. This property is meant to be set to the data object it visualizes. If you don't explicity define a source of a binding, it takes the data context by default.
The DataContext property inherits its value to child elements. So you can set the DataContext on a superior layout container and its value is inherited to all child elements. This is very useful if you want to build a form that is bound to multiple properties of the same data object.
<StackPanel DataContext="{StaticResource myCustomer}">
<TextBox Text="{Binding FirstName}"/>
<TextBox Text="{Binding LastName}"/>
<TextBox Text="{Binding Street}"/>
<TextBox Text="{Binding City}"/>
</StackPanel>
ValueConverters
If you want to bind two properties of different types together, you need to use a ValueConverter. A ValueConverter converts the value from a source type to a target type and back. WPF already includes some value converters but in most cases you will need to write your own by implementing the IValueConverter interface.
A typical example is to bind a boolean member to the Visibility property. Since the visibility is an enum value that can be Visible , Collapsed or Hidden , you need a value converter.
<StackPanel>
<StackPanel.Resources>
<BooleanToVisibilityConverter x:Key="boolToVis" />
</StackPanel.Resources>
<CheckBox x:Name="chkShowDetails" Content="Show Details" />
<StackPanel x:Name="detailsPanel"
Visibility="{Binding IsChecked, ElementName=chkShowDetails,
Converter={StaticResource boolToVis}}">
</StackPanel>
</StackPanel>
The following example shows a simple converter that converts a boolen to a visibility property. Note that such a converter is already part of the .NET framework.
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
if (value is Boolean)
{
return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
Tip: you can derive your value converter from MarkupExtension and return its own instance in the ProvideValue override. So you can use it directly without referencing it from the resources.
Another Tip: When you get the error "No constructor for type '...' has 0 parameters.", you need to add an default constructor to your converter, even it's not needed. Just for the WPF designer.
Last modified: 2011-03-12 22:32:33
Copyright (c) by Christian Moser, 2011.
Comments on this article
Show all comments
|
Ronak Babel | |
|
Commented on 17.March 2011 |
Some more details will be added advantage...
|
|
|
|
Paul | |
|
Commented on 23.March 2011 |
What about something like this. I'm using MVVM and I bind WindowViewModel as a DataContext to MainWindow. Inside WindowViewModel I have some objects like DocumentViewModel which has also some properties. How to bind for example properties of DocumentViewModel.Caption to MainWindow label (Label.Text). But without setting DocumentViewModel as Context of my Label! Can I somehow define terget path for this kind of binding?
|
|
|
|
Sanjay Patolia | |
|
Commented on 26.March 2011 |
Nice one
|
|
|
|
Sanjay Patolia | |
|
Commented on 26.March 2011 |
In beginning, you discussed that source property is a .Net Property and Target property is DependencyProperty. In case of Binding text of Element textbox where these source property and target property comes into the picture.?
|
|
|
|
Rachna | |
|
Commented on 12.April 2011 |
Your site is really helpful! Looking forward to more posts!! Well Done.
|
|
|
|
JC | |
|
Commented on 4.May 2011 |
Hi! How do you do that, but instead of an internal control (CheckBox) a local var, as in, Visibility="{Binding (MyClass.myVar)}"? I tried a lot of solutions, but none come with good results.
|
|
|
|
gg | |
|
Commented on 24.May 2011 |
good
|
|
|
|
subhash | |
|
Commented on 8.June 2011 |
Good article
|
|
|
|
Santosh | |
|
Commented on 15.June 2011 |
Very good post for beginer
|
|
|
|
ds | |
|
Commented on 18.June 2011 |
Thanks for the information! Great site.
|
|
|
|
nice one | |
|
Commented on 27.June 2011 |
nice one
|
|
|
|
skynet | |
|
Commented on 30.June 2011 |
good, nice.
|
|
|
|
Mohit | |
|
Commented on 11.July 2011 |
but i m confused with how can we use databinding with listbox , i get little solution about it in http://get-solution.in
|
|
|
|
Mohit | |
|
Commented on 11.July 2011 |
but i m confused with how can we use databinding with listbox , i get little solution about it in http://get-solution.in
|
|
|
|
Ershad | |
|
Commented on 13.July 2011 |
Excellent article with a nice visual representation. Thanks a lot.
|
|
|
|
Ershad | |
|
Commented on 13.July 2011 |
Excellent article with a nice visual representation. Thanks a lot.
|
|
|
|
noor | |
|
Commented on 30.July 2011 |
FIT
|
|
|
|
SamTheDev | |
|
Commented on 7.August 2011 |
thx a lot bro ... very cool tuto ina very simple way
|
|
|
|
anil kishor... | |
|
Commented on 12.August 2011 |
nice website for Initial user to learn
|
|
|
|
rwg | |
|
Commented on 17.August 2011 |
How do you do runtime data binding?
|
|
|
|
sari | |
|
Commented on 18.August 2011 |
nice
|
|
|
|
Jared | |
|
Commented on 30.August 2011 |
I have a few more examples like some have asked for here:
<a href="http://www.rhyous.com/2011/02/22/binding-visibility-to-a-bool-value-in-wpf/">Binding Visibility to a bool value in WPF</a>
|
|
|
|
Lakmal | |
|
Commented on 31.August 2011 |
This is simply great...
|
|
|
|
Sandip | |
|
Commented on 14.September 2011 |
Very Nice..!!
|
|
|
|
Sandip | |
|
Commented on 14.September 2011 |
Very Nice..!!
|
|
|
|