Data-binding To A Simple C# Class (WPF or Silverlight)

When composing a WPF view sometimes you need to ‘bind’ a property of one of your widgets to some kind of information source. WPF’s data binding capabilities provide a way to accomplish this very easily in XAML for a range of scenarios. Here’s a trivial example.

Let’s say you want a TextBox to get it’s text from an object of your own C# class. Let’s contrive a gnarly little sample class to serve as our data source that just holds a single property:

namespace HurstOnWpfDataBinding1
{
    public class Person
    {
        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }
 
        private string _firstName = "Aline";
    }
}

Consider this to be your “view-model”; in your XAML you bind to it using this syntax:

<TextBox Text="{Binding Path=FirstName}" />

What you are saying with this, in effect, is to get it’s value from the FirstName property of the binding source. You can get values only from properties – not from instance variables.

You can leave out the “Path” part – leaving this..

<TextBox Text="{Binding FirstName}" />

 

Where do we specify the binding source? One way is to simply do that in code; in the constructor after InitializeComponent, or in your event handler for the Loaded event:

public MainWindow()
{
    InitializeComponent();

    // Set the binding source here.
    MyClass viewModel = new MyClass();
    this.DataContext = viewModel;
}

 

Now it should work – when your Window pops up on the screen your TextBox fetches it’s text content from the FirstName property of your MyClass. Juuuust peachy.

But.. if you leave it as it is here, your TextBox won’t continue to update it’s text whenever the FirstName property changes! Why? Because it has no way of knowing; it fetches the property value just once as it initializes itself and renders itself on-screen.

Let’s fix that. We can use DependencyProperties, but for now why don’t we just reach for the simplest way available.

Change your source class to implement the INotifyPropertyChanged interface. This makes it send a notification to your XAML-defined TextBox of any important changes whenever you set a new value for that property. Here’s that same source class, with two essential changes. Take careful note of the change in your FirstName property…

 

using System.ComponentModel; // for INotifyPropertyChanged

namespace DesignForge
{
    public class MyClass : INotifyPropertyChanged
    {
        // This next region of code, is step ONE (of two) of what you need
        // to support the INotifyPropertyChanged interface.
        // I usually just copy it from a previous piece of code – it just works,
        // or, put it within a base-class.
        #region INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

        protected void Notify(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion INotifyPropertyChanged implementation

        // This is step TWO.
        // For each of your properties whose changes you want to track
        // (that is, to cause the data bindings to update),
        // add the call to Notify within the setter as I did below.
        // The string that you put as the parameter to Notify,
        // must to be exactly the same as the name of the property
        // (just copy-paste it and it'll rarely be a source of mistake).
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                // Do nothing unless the new value is different..
                if (value != _firstName)
                {
                    // Set the value.
                    _firstName = value;
                    // This next line is the only change within this property.
                    // Notify anyone who cares about this.
                    Notify("FirstName");
                }
            }
        }

        private string _firstName = "Naira";
    }
}

 

Now run your app and you should be seeing your GUI fields updating themselves to track the changes in your source class. This is the simplest example of a one-way binding and handles probably the majority of cases of this nature. Subsequent posts will cover more scenarios. Please shoot back a note to me if you spot any mistakes, problems or additional insight.

James W. Hurst

216 thoughts on “Data-binding To A Simple C# Class (WPF or Silverlight)”

  1. It’s the best time to make some plans for the future and it is time to be
    happy. I’ve read this post and if I could I want to
    suggest you few interesting things or tips. Perhaps you can write next
    articles referring to this article. I want to read more things
    about it!

  2. Woah! I’m really loving the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between superb usability and appearance.

    I must say you have done a awesome job with this. In addition, the blog loads super fast for me on Internet explorer.
    Exceptional Blog!

  3. 먹튀사이트 검증사이트 먹튀폴리스입니다.
    먹튀폴리스는 신규는 물론 오픈된 먹튀사이트를 철저히 먹튀검증하여 먹튀없는 시대를 만들어가고
    있습니다. 먹튀폴리스를 사랑하는 여러분의 많은
    호응바랍니다. 여러분의 충실한 먹튀검증 사이트가 되도록
    노력하겠습니다.

  4. Narconon Drug Abuse Prevention presenters are trained so that
    they can cogently present material regarding a wide range of drugs.
    There is, however, no single presentation which is unvaryingly followed, for three reasons, First, there are very considerable differences in the cognitive
    skills of pre-teens and those of teenagers. Second, there is likewise a
    great difference in the awareness and experience of
    drugs between the two groups. And, thirdly,
    students in classes of the same grade in different schools or areas present
    very different problems and concerns. Thus, as the presenter interacts with the
    students, the nature of their questions and the level of their argumentation skills
    necessitate different approaches for different groups. https://wowviaprice.com/ viagra connect usa

  5. We’re a group of volunteers and opening a new
    scheme in our community. Your site provided us with valuable info
    to work on. You have done an impressive job and our entire community
    will be grateful to you.

  6. This design is spectacular! You most certainly know how to keep
    a reader entertained. Between your wit and your videos, I
    was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.
    I really enjoyed what you had to say, and more than that, how you presented it.
    Too cool!

  7. I think that everything typed made a lot of sense. But, what about this?
    suppose you were to write a killer headline?
    I mean, I don’t wish to tell you how to run your website, but suppose you added a post title that
    grabbed a person’s attention? I mean Data-binding To A Simple C# Class (WPF or Silverlight) – JamesHurst.dev is a little vanilla.
    You might look at Yahoo’s front page and note how they create news titles to grab viewers
    to click. You might add a related video or a related
    pic or two to grab readers interested about everything’ve got to
    say. In my opinion, it would make your posts a little bit
    more interesting.

  8. It’s perfect time to make some plans for the future and it’s time to be happy.
    I’ve read this post and if I could I want to
    suggest you few interesting things or suggestions. Perhaps you can write
    next articles referring to this article. I want to read more things about it!

  9. Yesterday, while I was at work, my sister stole my iphone and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My
    iPad is now destroyed and she has 83 views. I know this is totally
    off topic but I had to share it with someone!

  10. You are so cool! I don’t suppose I’ve read a single thing like this before.

    So wonderful to find somebody with original thoughts
    on this subject. Seriously.. many thanks for
    starting this up. This website is one thing that is required on the web, someone with
    a little originality!

  11. you are truly a excellent webmaster. The site loading velocity is amazing.
    It kind of feels that you’re doing any unique trick. Furthermore, The contents
    are masterpiece. you have done a great activity in this topic!

  12. What i do not realize is actually how you’re not really a lot
    more smartly-liked than you may be now. You’re very intelligent.
    You realize therefore considerably with regards to this subject, produced me in my view
    imagine it from so many varied angles. Its like women and men don’t seem to
    be fascinated except it’s one thing to do with Lady gaga!
    Your individual stuffs outstanding. At all times take care of it up!

  13. Those with ongoing diarrhea should seek medical attention if they experience: Diagnosing diarrhea itself
    isn’t always as simple as one might think, said Lustbader,
    who noted that people often experience changes in their bowel movements and think that they have diarrhea when, in fact, they do not.
    https://saleviabuy.com
    where to buy female viagra

  14. I do not know if it’s just me or if everyone else encountering issues
    with your site. It appears like some of the text within your posts are
    running off the screen. Can somebody else please comment and let me know if this is happening
    to them as well? This may be a issue with my browser because I’ve
    had this happen before. Thank you

  15. I love your blog.. very nice colors & theme.

    Did you create this website yourself or did you hire someone to do
    it for you? Plz respond as I’m looking to
    create my own blog and would like to know where u
    got this from. thanks a lot

  16. This is very interesting, You are a very skilled blogger.
    I have joined your rss feed and look forward to seeking
    more of your magnificent post. Also, I’ve shared your web site in my social networks!

  17. I was recommended this blog by way of my cousin. I’m not certain whether or not this publish is written by way of him as no one else recognise such
    special approximately my trouble. You are incredible!
    Thanks!

  18. My brother suggested I might like this website. He was
    totally right. This post truly made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  19. Hey I know this is off topic but I was wondering if you knew of any widgets I could
    add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some
    experience with something like this. Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your new updates.

  20. Hello There. I found your weblog the usage of msn. This is
    an extremely neatly written article. I will make sure to bookmark it and return to learn more of
    your helpful information. Thanks for the post. I will definitely return.

  21. Today, I went to the beachfront with my kids.
    I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear. She never wants to go back!
    LoL I know this is totally off topic but I had to tell someone!

Leave a Reply