Geeks With Blogs
Tanveer Ibn Haresh
Many get confused over the two way databinding concept. This is usually  done by implementing INotiyPropertyChanged interface.You can find many examples with INotiyPropertyChanged if you google for it.  Here I am presenting a very basic example of WPF databinding to show its advantages.

Create a WPF Application called "TwoWayDataBinding". You have app.xaml and Window1.xaml. Add one class called Customer to the project. The code for the class is bellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TwoWayDataBind
{
    class Customer
    {
        private string m_name;

        public string Name
        {
            get { return m_name; }
            set { m_name = value; }
        }
        private string m_State;

        public string State
        {
            get { return m_State; }
            set { m_State = value; }
        }
    }
}

We have two string  properties called  name and state in the customer class. We are going to use this class as the datasource for our  WPF form.

Now look at the XAML code for the Window1.xaml file. The explanations will follow.

<Window x:Class="TwoWayDataBind.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myapp="clr-namespace:TwoWayDataBind"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <myapp:Customer x:Key="Cust2" Name="Hansen" State="Arizona"/>
    </Window.Resources>
    <Grid x:Name="Grid1"  DataContext="{StaticResource Cust2}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0">Name:</TextBlock>
        <TextBlock Grid.Column="0" Grid.Row="1">State:</TextBlock>
        <TextBox x:Name="TextBox1" Grid.Column="1" Grid.Row="0" Text="{Binding Path=Name}"></TextBox>
        <TextBox x:Name="TextBox2" Grid.Column="1" Grid.Row="1" Text="{Binding Path=State}"></TextBox>
        <Button Grid.Column=" 1" Grid.Row="2"   Name="button1" Click="OnClicked">Control To Context</Button>
      
    </Grid>
</Window>

In the first  line the class Name for the Window1 form is specified.

Next, there are two XML namespace declarations. The first declaration maps the overall Windows Presentation Foundation (WPF) namespace as the default:

The second declaration maps a separate Extensible Application Markup Language (XAML) namespace, mapping it (typically) to the x: prefix.

Coming on to the next part, you can map XML namespaces to assemblies using a series of tokens within an xmlns prefix declaration, similar to how the standard WPF and XAML namespaces are mapped to prefixes.We are mapping a xml namespace myapp with the TwoWayDataBind Assembly . This will be  used in the next segment.

In the next section,we are declaring a resource dictionary. Microsoft defines these dictionaries as "Resource dictionaries that can be defined completely or partially in Extensible Application Markup Language (XAML) are typically created as a property element, and are typically on the root element for any individual page or for the application. Placing the resource dictionary at this level makes it easier to find from individual child elements in the page (or from any page, in the application case)". We are declaring a resource for  window element, so that all child elements of the window can access it. You can also define resources for page,grid and other elements. We used the xml namespace myapp, that we mapped to our application assembly section. We are accesing the customer class of the TwoWayBindingAssmbly with myapp:Customer. We are defining a key for the resource, which will be used for accessing it from other elements in the form. We are also specifying values for the two customer properties.

Next we define the grid element for the WPF form. Look at the part  DataContext="{StaticResource Cust2}. This is the important part for defining the databinding for our form. DataContext is a dependency property. It gets or sets the data context for an element when it participates in data binding. So are defining a datacontext for the Grid element here.We are defining the datacontext using the StaticResource. Static Resource provides a value for any XAML property attribute by looking up a reference to an already defined resource. That defined resource here is obviously Cust2, which is nothing but our customer class.

The Next 11 lines defines the form design xaml, as any wpf developer would find it  easy to understand. Coming to the part of our interest :

        <TextBox x:Name="TextBox1" Grid.Column="1" Grid.Row="0" Text="{Binding Path=Name}"></TextBox>
        <TextBox x:Name="TextBox2" Grid.Column="1" Grid.Row="1" Text="{Binding Path=State}"></TextBox>

   Here we are binding the text properties of the text boxes to the properties of the customer class. MSDN describes WPF databinding as "

To use WPF data binding, you must always have a target and a source. The target of the binding can be any accessible property or element that is derived from DependencyProperty—an example is a TextBox control's Text property. The source of the binding can be any public property, including properties of other controls, common language runtime (CLR) objects, XAML elements, ADO.NET DataSets, XML Fragments, and so forth. To help you get the binding right, WPF includes two special providers—the XmlDataProvider and the ObjectDataProvider."

The syntax we are using here is called attribute syntax. It condenses the data binding code inside of the Text attribute of the TextBox. Basically, the Binding tag gets pulled inside of the curly braces along with its attributes. "Path" is one of the Four components of Binding class. It gets or sets the path to the binding source property.  So here we are setting the two properties of  the customer class the the Binding source property of the textbox's text propety.

We have a button on the form and it has a click event method defined. Here is the code for the codebehind for the form.

Window1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;



namespace TwoWayDataBind
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
           
        }

        private void OnClicked(object sender, RoutedEventArgs args)
        {
            Customer c1=Grid1.DataContext as Customer;
          
            TextBox1.Text = c1.State;
           
        }
      
    }
}

Now if you run the project  you will see.


So the textbox's are bound to the customer properties. We can see the values of the customer object in the texboxes.So this is one side of the databinding...the target object is getting update by the value of the data source. Now write something in the state textbox and click the button. What do you see? The Name textbox getting populated with the value of the State textBox.

If we look at the code for the button click:

Customer c1=Grid1.DataContext as Customer;
 TextBox1.Text = c1.State;

We are not assigning the new value to the customer class or datacontext. As we type  in the State textbox, the dataContext  is getting updated. So when we assign the datacontext's State value to the Name textbox, we see it gets populated with the new value that is entered. Isn't it just fantastic?





Posted on Monday, February 16, 2009 12:14 PM WPF | Back to top


Comments on this post: WPF Two way databinding explained

# re: WPF Two way databinding explained
Requesting Gravatar...
Thank you for such a straighforward example. So may examples try to overdo it, but yours is short and sweet and therefore, allows the idea to sink in before adding so many bells and whistles.
Left by Lagaidh Smif on Aug 28, 2009 8:59 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
It's useful example, thanks!
Left by Electric garage heaters on Jan 23, 2010 2:28 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
Thanks for useful code. And screenshot.
Left by caralluma fimbriata on Feb 23, 2010 4:53 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Data binding is a powerful capability that has finally matured in Windows Forms 2.0 through the capabilities in the .NET Framework classes, combined with the rich designer support provided by Visual Studio 2005.
Left by liste de casinos en ligne on Mar 05, 2010 4:04 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
thanks your code
Left by cheap true religion jeans on Apr 05, 2010 3:45 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
it was very very helpful for me ! really helped me in my university task ! thanks a bunch
Left by stock tips on Aug 01, 2010 9:25 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
Fantastic post very well written and it contains many useful facts. I appreciated your professional manner of writing this post.
Left by Forex Trading on Dec 11, 2010 4:01 AM

# Mr
Requesting Gravatar...
I can understand.
Left by seo nepal on Dec 20, 2010 3:10 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
my problem, what if the client has a 'Cancel' button. how does it revert back without having to reread the database?
Left by geordie on Jan 05, 2011 1:27 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
Awesome! I'll bookmark your website.
Left by Chiang Mai Travel on Jan 07, 2011 1:36 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
It is an interesting approach. I commonly see nothing exceptional views on the subject, but yours is written in a very unusual way. No doubt I will get back to your website for additional information.
Left by Nissan Sentra Windshield on Jan 26, 2011 12:45 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
Useful post, i have just bookmarked this blog. will visit again.
Left by Hotels in Huntington Beach on Feb 07, 2011 9:47 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
ey I love your style I will subscribe for your feed please keep posting!
Left by Hotels in Huntington Beach on Feb 07, 2011 9:49 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
I am really impressed by WPF databinding. Thanks for posting the examples
Left by pam on Feb 14, 2011 11:49 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
It is an interesting approach. I’ll be waiting for your next article.
Left by san francisco party bus on Feb 15, 2011 10:29 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Thank you for such a straighforward example.
Left by City Limo on Feb 15, 2011 10:31 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
It's an interesting approach. Without doubt, I'll go back to your website for more information.
Left by san diego limo service on Mar 03, 2011 3:59 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
I will just become a great follower and Just want to say your article is striking.The clarity in your post is simply striking and I can take for granted you are an expert on this subject.
Kidney beans
Left by john 6775 on Mar 05, 2011 2:17 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
This is a smart blog.I mean it.You have so much knowledge about this issue, and so much passion.You also know how to make people rally behind it, obviously from the responses.Youve got a design here thats not too flashy, but makes a statement as big as what youre saying. Great job.
usa property investment
Left by joseph on Mar 05, 2011 2:19 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
I am very enjoyed for this blog.Its an informative topic.It help me very much to solve some problems.Its opportunity are so fantastic and working style so speedy. I think it may be help all of you.Thanks a lot for enjoying this beauty blog with me.I am appreciating it very much! Looking forward to another great blog. Good luck to the author! all the best!
Property management
Left by joseph on Mar 05, 2011 2:20 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
I found your website perfect for my needs.It contains wonderful and helpful posts.I have read most of them and got a lot from them.To me, you are doing the great work.
Left by Minnesota web design on Mar 05, 2011 7:35 AM

# reply
Requesting Gravatar...
Saying thanks will not just be sufficient,for the wonderful clarity in your writing.I will immediately grab your rss feed to stay for any updates.Pleasant work and much success in your business dealings!
Left by spa gift certificates ann arbor on Mar 07, 2011 5:41 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.
Left by speed reading software on Mar 07, 2011 6:14 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Just want to say your article is astounding.The clarity in your post is simply spectacular and I can assume you are an expert on this field.Well with your permission allow me to grab your rss feed to keep up.
Left by pet bird supplies on Mar 08, 2011 2:00 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
I probably won't be able to just go buy a block of wood that is the perfect size, but call a few local lumber yards to see what they have. Also make a couple calls to cabinetry shops, they may have the right size wood and will definitely help you out if you want a small box built to take the place of a solid piece.
Left by eulogy samples on Mar 09, 2011 2:27 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Great post! My friend was convinced that she need expert to solve her problem related to sculpture bases. But some people here have brilliant ideas that could also help you find a good answers. Give them a shot.
Left by last longer on Mar 09, 2011 2:29 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
I Just want to say your article is striking. The clearness in your post is simply spectacular and i can take for granted you are an expert on this field. Thanks a million and please keep up the effective work.
Left by talking dirty on Mar 09, 2011 2:30 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Way back in 2003, the Journal of Alternative and Complimentary Medicine's Oct. 9th issue reported a study finding that Tai Chi "could decrease blood pressure and results in favorable lipid profile changes and improve subjects' anxiety status. Therefore, Tai Chi could be used as an alternative modality in treating patients with mild hypertension, with a promising economic effect." This study laid out a way to save our society, perhaps billions of dollars annually, and possibly save some patients with mild chronic hypertension the potential negative side effects of chronic lifelong medication. However, this largely hasn't occurred.

I caught a glimpse why when I was staying in the beautiful mountain town of Otavala, Ecuador, with a woman known for her knowledge of traditional Indian medicines. A tour of young American medical students stopped here to listen and learn from the Indian woman's tour of her herbal gardens. As I followed them, I asked a group of young bright medical students if they were aware that Tai Chi was found to reduce high blood pressure. One lovely young woman replied, "Oh, yes, I've heard that, but I would never prescribe it."

I asked why, and she responded that she couldn't because she didn't know if it would work. Although Tai Chi studies do show that Tai Chi indeed helps lower high blood pressure, it is true that it does not reduce it in every person. However, it is also true that every drug prescription does not work on every person either. I suggested to the young medical student that she consider that many times I've been to the doctor, and he's pulled out a prescription pad and explained, "Let's give this a try, and see how it works for you, and if it doesn't do the job, we'll try something else." Most of us are familiar with this, and by the confused look on the student's face, I'm assuming her memory banks were bringing up similar images.
Left by chi flat iron on Mar 09, 2011 7:36 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
This was very helpful.I was painfully uploading one file at a time. I had tried zipping files together and uploading, but then I couldn't unzip on the other end without permissions.This is much easier and straightforward.
Left by no dumping signs on Mar 11, 2011 12:51 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
This web page is very colorful which I hasn't seen till now.Your work is very good and I appreciate you and hoping for some more informative posts. Thank you for sharing great information to us.
Left by local movers chicago on Mar 11, 2011 12:53 AM

# lia james
Requesting Gravatar...
I like every post in this blog. Really a nice work has done. I appreciate the blog owner.
Left by deliver flowers Canada on Mar 11, 2011 2:16 AM

# JOhn carrie
Requesting Gravatar...
Interesting blog. It would be great if you can provide more details about it. Thanks you.
Left by mothers day flowers delivery Mal on Mar 11, 2011 2:19 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
The Smart Strip automatically detects when you have turned an item off and completely cuts power to a device so it stops drawing electricity and provides surge protection.
Left by Car Finance on Mar 21, 2011 1:46 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
I like every post in this blog. Really a nice work has done. I appreciate the blog owner.
Left by cheap wedding invitation on Mar 22, 2011 12:12 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
item off and completely cuts power to a device so it stops drawing electricity and provides surge protection.
Left by twin screw extruder on Mar 22, 2011 1:01 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
This is very nice and cool post.I was waiting for this type article and I have gained some useful information from this site. Thanks for sharing this information.Keep blogging.
Left by gold silver ira on Mar 25, 2011 5:16 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Fabulous post,This is such a great resource that you are providing us.
Left by historical gold price on Mar 25, 2011 5:17 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
The said post here is very informative. I am impressed as to the ways in which the author delivered the message to us readers. I am curious as to the details and have read and got my answers to my query. It is nice to know that this one here really exist. I would love to track your future posts.
Left by India Tours on Mar 31, 2011 5:55 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Do you like movies? What players you often use ? Recommend you a website, and i promise it has everything that you want.p90x workout dvd
Left by p90x workout dvd on Apr 08, 2011 4:25 AM

# re: WPF Two way databinding exp
Requesting Gravatar...
Your blog make me feel happy Tory Burch Flats
Left by Cheap Tory Burch Flats on Apr 13, 2011 2:12 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Your instruction was useful and I'm going to use Tory Burch Outlets Sale, my grammar book are not so clear:)

Thanks you once again !
Left by Tory Burch Outlets Sale on Apr 14, 2011 9:55 PM

# 小姐
Requesting Gravatar...
I am usually to blogging and i actually respect your content. The article has actually peaks my interest. I am going to bookmark your website and maintain checking for new information.



Left by trx on Jun 24, 2011 3:11 AM

# re: WPF Two way databinding explained
Requesting Gravatar...
Really useful information..
Left by sudeep on Sep 27, 2012 6:39 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
Nice illustration, Thanks you
Left by Online Training on Nov 09, 2012 11:18 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
great information and understandable.
Left by toqeer on Feb 11, 2013 6:26 PM

# re: WPF Two way databinding explained
Requesting Gravatar...
Great, no ego in the way, very good and simple explanation
Left by Jean Offenberg on Mar 19, 2014 10:43 PM

Your comment:
 (will show your gravatar)


Copyright © Tanveer-Ibn-Haresh | Powered by: GeeksWithBlogs.net