Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  


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
Bob WIllsie
Commented on 18.May 2009
Can you cover binding in more detail? I expected to be able to drag and drop fields from a data source onto a form and have binding happen automatically. (Like it does in a standard VB form application.)

However, I am unable to do this in a WPF application.

Consequently, I cannot figure out how to bind the WPF form field to the database field.

FYI, I am using VB 2008 Express edition so maybe I have to code this manually?
Christian Moser
Commented on 19.May 2009
Hi Bob,
I think it's more a missing feature of the Visual Studio WPF designer, that does not support drag&drop data wiring. In Expression Blend you can do databinding by dragging properties of a data source to elements on the user interface.
So maybe it's worth downloading the free preview version of Expression Blend 3 and play around with data sources. I hope this helps you.

Christian
jeevan mummadi
Commented on 1.June 2009
how to bind database values to wpf textboxes using sql server.
give me sample code.
jeevan mummadi
Commented on 1.June 2009
how to bind database values to wpf textboxes using sql server.
give me sample code.
Bax
Commented on 10.June 2009
I think you are doing an excellent job, but I do believe your data-binding examples need more punch, since this is an extremely difficult concept to grasp for a beginner in WPF. I would suggest this area needs more simple examples and concepts explained in further detail. Otherwise, great work on the other topics, just need to expand a little here.
Tarık Turalp
Commented on 14.June 2009
Hi,it is nice article,hovewer i don't understand.
what do we exactly here?

Note : i don't understand ValueConverter
rinkesh
Commented on 17.June 2009
how to bind an image
Hani Almousli
Commented on 8.July 2009
Thanks very much for this helpful site. Please i a have a severe problem when i am trying to bind a list view to a List<>. I want the changes,addition and deletion from List<> to be reflected directly to the list control. I tried one way binding,two way,property changes without benefit.Please can you explain it with a simple example because i could not find a solution for this problem unless replicating data which is very bad.Although please could tell me what is the difference between DataContext and itemsSource properties.
With my best regard .

Ruba
Commented on 30.July 2009
Your articles are simple and explainable!simply superb!
Abhishek
Commented on 1.August 2009
Please discuss binding for Drop Down Lists in details.
Daniel
Commented on 19.August 2009
have you video for thas......merci
zolyita
Commented on 23.August 2009
I loved the way you explain. Just to the point. Did you see on line "Databinding can be unidirectional (source -> target or target <- source), or bidirectional (source <-> target)". Please change direction of target<-source to target->source.
With this, i will appreciate if you add a post on how to bind complex data such as list of authors and books into the same control. Thanks
Prabhakar
Commented on 30.September 2009
Simple complete application will help more than piece of code.
Michael
Commented on 13.October 2009
Christian, you have *no* idea how helpful your tutorials have been -- between your site and Adam Nathan's book, I think I'm going to actually figure this stuff out! Many thanks!
deepti
Commented on 15.October 2009
how to bind sqlserver database with wpf
ramesh
Commented on 30.October 2009
good...but i expect more from binding data.....
Malini
Commented on 4.November 2009
Hi, since i am novice to this WPF, i would like to enquire more info in dynamic binding with sql datasets. Could you kindly provide more details on this
Hicham
Commented on 3.December 2009
thank you very much for what you have done!
Eric
Commented on 11.December 2009
The visibility converter example is awesome. Just what i needed
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!
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
Vikas
Commented on 31.August 2010
The site looks awesome and so are the contents.... Keep going mate
sumit sharma
Commented on 6.September 2010
awesome article keep it up buddy :D
Arch
Commented on 30.September 2010
Hi,
Please show the output of various markup code fragments, as we are dealing with something which depends on look and feel.It would be easier to understand effect of code.
starbros
Commented on 1.October 2010
Useful information - one question I cannot find the answer to: When is "path" required in the binding expression? I see it sometimes used and other times only the property is shown: e.g.: {Binding Name} or {Binding Path=Name} - are these equivalent? Thx
mathew
Commented on 4.October 2010
I have a resource dictionary in 'resources' folder. I have a xaml file inside 'UI' folder, To bind to an item in the above said resourcedictionary within the xaml file, what should I do? whatever I do, it always says, binding cannot be resolved. Any idea?
Amberale
Commented on 6.October 2010
Incomplete. It is really difficult to find an end-to-end dialog example, object is pulled from the middle tier, loaded into the dialog, and changes updated to the object when the Save button is clicked.
John
Commented on 22.October 2010
Thanks Christian. Good work. Here is a link to more details: http://msdn.microsoft.com/en-us/library/ms752347.aspx
John
Commented on 22.October 2010
Binding declaration syntax:
http://msdn.microsoft.com/en-us/library/ms752300.aspx
Sam
Commented on 25.October 2010
Hii Guys......
Please reply the meaning of the return statement with in the IF condition
Thanks in advance.......


if (value is Boolean)
{
return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
Sam
Commented on 25.October 2010
I found somebody has problem with Control events in the Property window.
Install VS2008 SP1.

Happy Programming...
Christian Moser
Commented on 25.October 2010
Hi Sam,

this statement means: if the value is true it returns "Visible", else "Collapsed".
Sam
Commented on 26.October 2010
Thanks Christian..
indru
Commented on 26.October 2010
Very worst
Demon
Commented on 26.October 2010
if (value is Boolean)
{
return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;
}


No proper syntax. will not retrurn any values
james
Commented on 26.October 2010
Who the hell is this indru
till
Commented on 26.October 2010
Could you stretch that out a bit? F.ex. where's the code-behind?
venila
Commented on 27.October 2010
It is very interesting.....Thanks a lot
viknesh
Commented on 1.November 2010
wonderfull site for wpf...
SonnyMal
Commented on 8.November 2010
Great WPF site, the articles are kept simple and to the point, great resource for learning WPF.
Raji
Commented on 15.November 2010
Too good and easy
Scud
Commented on 19.November 2010
In binding example, I do not understand why you written UpdateSourceTrigger=PropertyChanged? Example works without that just like this:

<StackPanel>
<TextBox x:Name="txtInput" />
<Label Content="{Binding Text, ElementName=txtInput}" />
</StackPanel>
Mono
Commented on 26.November 2010
Christian, first of all thanks for your post. I have a question.
I would like to Enable a Button if a ListBox has a SelectedItem AND if that Item has the MyBoolProperty set to true.
I have tried this:

<ListBox Name="MY_LB>
</ListBox>
...
<Button Content="SomeContent" >
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource INDEX_TO_BOOL}">
<Binding ElementName="MY_LB" Path="SelectedIndex"/>
<Binding ElementName="MY_LB" Path="SelectedItem.MyBoolProperty" />
</MultiBinding>
</Button.IsEnabled>
</Button>

...but setting two different kind of source doesn't achieve the logical AND that I need. How can I do that? Many thanks anyway!
santhosh
Commented on 29.November 2010
ore idiot
Sateesh...
Commented on 1.December 2010
Very Informative and Good one
Thanks.
hui
Commented on 2.December 2010
excellent! Thanks
Nitin
Commented on 27.December 2010
great job...
hong
Commented on 11.January 2011
good ...
Vinomanoharan
Commented on 13.January 2011
Nice one :-), Thanks
Vinomanoharan
Commented on 13.January 2011
Nice one :-), Thanks
Vinomanoharan
Commented on 13.January 2011
Nice one :-), Thanks
Siva
Commented on 25.January 2011
It would be great if explained with more examples
OMENDRA PANDEY
Commented on 3.February 2011
Very nice cool :-)
Ravi
Commented on 7.February 2011
its really help full grt work..........
Sandeep
Commented on 8.February 2011
Nice wauy to understand the WPF
vinod
Commented on 28.February 2011
i think no proper decoupling between source code and code behind when come to the databinding in wpf
Dennis
Commented on 7.March 2011
I'm a beginner to WPF programming and Binding is still a little over my head, but thanks for helping me grasp this concept.
ram
Commented on 10.March 2011
very good source for beginners. Thank you Mosers. Keep posting.
Sunil K
Commented on 16.March 2011
Very Helpful site.
tehDude
Commented on 17.March 2011
I bet this fag in the header would like to bind his cock to his boyfriends mouth. Stop wearing sweaters from the 1980's faggot..
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=&quot;{Binding (MyClass.myVar)}&quot;? 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:
&lt;a href=&quot;http://www.rhyous.com/2011/02/22/binding-visibility-to-a-bool-value-in-wpf/&quot;&gt;Binding Visibility to a bool value in WPF&lt;/a&gt;
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..!!

Name
E-Mail (optional)
Comment