Bookmark and Share Share...    Subscribe to this feed Feed   About me...


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.




 Comments on this article

Show all comments
ShaikAli
Commented on 18.December 2009
The complete example is her : http://www.switchonthecode.com/tutorials/wpf-tutorial-using-the-listview-part-3-in-place-edit
Curious
Commented on 5.January 2010
So how do we bind properties of a specific object to element attributes? I'm using an ObjectDataProvider to bind class properties to the attributes, and it works when the properties have pre-defined values or when I set the values via a specific object. What I want to do is to access individual objects' properties instead of the class properties.

Any help is greatly appreciated. Keep up the good work!
יוסי
Commented on 22.February 2010
×תר × ××ר, ×× ×ת××× ××× ××¢×צ×× ×××צ×× ×
××¤× ×××× ×××©× ××
יוסי
Commented on 22.February 2010
×תר × ××ר, ×× ×ת××× ××× ××¢×צ×× ×××צ×× ×
××¤× ×××× ×××©× ××
willian
Commented on 1.March 2010
Please anyone can tell me if i want to bind data from table. Then what I've to do ?
To bind data in the list control
unknown
Commented on 3.March 2010
If you want to bind data from a table, it really depends on how you are retrieving the data. It all revolves around that. You can bind to a collection view source, an observable collection, poco, even an entity set...it depends on the design of your application and how many layers you have. Bind the data to the itemssource property on the list control
sharmi
Commented on 19.March 2010
hai everyone,

i ve a doubt where the events available for every control.i couldnt find d event for button control
sharmi
Commented on 19.March 2010
hai everyone,

i ve a doubt where the events available for every control.i couldnt find d event for button control
sharmi
Commented on 19.March 2010
hai everyone,

i ve a doubt where the events available for every control.i couldnt find d event for button control
sharmi
Commented on 19.March 2010
hai everyone,

i ve a doubt where the events available for every control.i couldnt find d event for button control
Lalit
Commented on 26.March 2010
As per your DataContext section, how StaticResource myCustomer is going to be use in Code. I'm expecting that we can populate item to myCustomer obecjt, which will be reflected in the UI. But No information found in this article..
Mehh
Commented on 26.April 2010
Hey--this example didn't completely solve the problem I have at {work/home/school}. I'm a lazy ass and I expect to be spoon fed this stuff. I'm sad :-(
Palak
Commented on 30.May 2010
it woulde be nice if you include more details. ?i find article bit vague and incomplete.
Shashank...
Commented on 3.June 2010
Awesome article for starters and interviews!
pardhu
Commented on 4.June 2010
Ã�êè à Ã�Ã�è, Ã�Ã� Ã�êÃ�Ã�Ã� Ã�Ã�Ã� Ã�âÃ�æÃ�Ã� Ã�Ã�Ã�æÃ�à Ã�
�ä� ���� ��é� ��
Mutia
Commented on 10.June 2010
I always do data binding in xaml.. can i do this with c# code only?
(http://mutiarar06.student.ipb.ac.id)
Pramod
Commented on 23.June 2010
good document for data binding
Tom
Commented on 8.July 2010
Good One
Memory
Commented on 15.July 2010
Very good,thank you
chang
Commented on 20.July 2010
what a post sir ji
Ameen
Commented on 25.July 2010
Very good introduction of Data binding.
negudda
Commented on 9.August 2010
ne gudda katla information
Mallesh
Commented on 16.August 2010
Please, Good In Eloboration.but We Expect Not Only Theoritical explaination also need Code Explaination
Christian Moser
Commented on 23.August 2010
Hey guys I hope you like this one because I copy and pasted it straight from another blog.
Vikas
Commented on 31.August 2010
The site looks awesome and so are the contents.... Keep going mate

Name
E-Mail (optional)
Comment
About Christian Moser