I Notify When Property Changes – Data Binding Reloaded

On my last post, what I said was pretty basic stuffs on data binding. Now I need to Nerd Up a bit. I mean today we’re gonna take a bit deeper dive into data bindings.  So, if you in case missed the last one on data binding, kindly read my last post on data binding.

So, as this is only a continuation, lets not reinvent the wheel. We’re gonna use the same PersonModel class we used last day because that’s really simple.

Before we get started, let’s get to know someone and his name is INotifyPropertyChanged. Before you get scared, lemme tell you something. This guy holds a very important key of MVVM pattern and practically he does a huge deal of heavy work. Now you might ask what the hell does he do that makes him so important? :S
Now if you believe you dont want to waste your time listening to me saying baby stuff, you can go here and get it by yourself, no baby stuff, rock solid geek material.

Now for the ones who prefer it from me, let me clarify stuff for you in the easiest way possible. The easiest way would be he’s a notifier, practically a mailman who rings your doorbell every time you get a mail, or your fire alarm, who sees a little fire and fies you. If you carefully see, all of these characters do one and one thing in common. They notify you when something important (a very property around you) changes. So, if you are an object of a certain class and you want to know when someone changes one of your property, who you should call? Yes, you should call INotifyPropertyChanged. Clear?

Now, wait wait? how? Call? Is he a method? Look at the name, the name starts with an capital “I”, that means he is an interface, you have to implement him on the class you want to.   So, lets see! Shall we? We’re using our PersonModel class from previous tutorial.

class PersonModel: INotifyPropertyChanged
    {

        private string _name;
        private string _age;
        private string _height;

        public string Name
        {
            get { return _name; }
            set
            {
                if (_name != value)
                {
                    _name = value;
                    NotifyPropertyChanged("Name");
                }
            }
        }

        public string Age
        {
            get { return _age; }
            set
            {
                if (_age != value)
                {
                    _age = value;
                    NotifyPropertyChanged("Age");
                }
            }
        }
        public string Height
        {
            get { return _height; }
            set
            {
                if (_height != value)
                {
                    _height = value;
                    NotifyPropertyChanged("Height");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

Looks like a lot of change has taken place ha? Well, truth to be told, yes , it kinda did. DONT GET SCARED. Lets see what we did here. Actually if you see closely we didn’t do much, we implemented the INotifyPropertyChanged and included a event named public event PropertyChangedEventHandler PropertyChanged; And you have to write this event every time you implement INotifyPropertyChanged. You might say what if I forget? Fear not! When you have written INotifyPropertyChanged right beside your class name, press ctrl +  . (dot) and you’ll see Visual Studio asking you to implement all its needed to implement! Easy ha?

Capture

So, you see, you practically dont have to remember this one. But what’s an event? :S An event is a certain situation when you want to invoke or do something. Like the change in the property. But you dont know what to do now, you want to decide when it happens. So what do you do? You write an event and when the certain situation comes you write it then.

So, with that out of the way, why did we write a private object of every property we wrote before? Because, we want to see which property changes. So, there’s a private object like _name for the public property “Name”. Now, if you see closely, the public property have get and set methods. In the get method we are returning the private object and in the set method we are checking whether the new value is same as the previous or not, if it is we set it and raise the event, otherwise we do nothing!

W-wait! raise an event? Well, we did write a method named NotifyPropertyChanged. Why? All it does that it checks whether a user has assigned anything to the event we declared before and if its not null, it fires or invokes it. If its null, it does nothing. Simply put if we want to watch any property, all we have to do is assign something to the event PropertyChanged. The NotifyPropertyChanged takes the name of the property and detects who has raised the event. Neat!

Okay, we need action, right? We need to change some property when the application is running, other wise we wont understand. But before we do that, let me ask you something again. Why are we even doing this? Because when the data inside an object changes , I mean the property changes, the view needs to know that it has changed and if it doesn’t know how it would update itself? We can’t bind them every time it changes. Can we? thats where INotifyPropertyChange comes real handy. Because it notifies the view that the data has changed and you sould update yourself too! 😉

Now lets add a button to the view just so we can update the data behind when we want.

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBox Height="70" HorizontalAlignment="Left" Margin="0,130,0,0" Name="Name" Text="{Binding Name}" VerticalAlignment="Top" Width="450" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="0,206,0,0" Name="Age" Text="{Binding Age}" VerticalAlignment="Top" Width="450" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="0,284,0,0" Name="Height" Text="{Binding Height}" VerticalAlignment="Top" Width="450" />
            <Button Content="Update Data" Click="Button_Click" Margin="0,361,0,159" ></Button>
        </Grid>

The UI looks like this right now.
UI Changed after update

Now, we added a click event on the button (we will not do this much in MVVM, will tell you later why). Let’s change that so we can update the data of the PersonModel object.

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            _personModel.Name = "Rishad";
            _personModel.Age = "24";
            _personModel.Height = "5.10";
        }

So, lets see whether it works or not, if I click Update Data, will the data in the textblocks change?

wp_ss_20130929_0001

Amazing! It does change! So, you see, that’s where INotifyPropertyChange comes handy. Hey! we didn’t use the event here by ourselves. Well, when it comes to the changes of views you don’t have to worry about that. When you want some changes based on a property you can call that event.

So, until next time, ciao. Next we’ll dig a bit more on binding modes and element binding. I might go for a video next time. I feel I can deliver better there.

Advertisements

One thought on “I Notify When Property Changes – Data Binding Reloaded

  1. Hi there! I know this is somewhat off topic but I was wondering which blog platform are you using for this site?
    I’m getting sick and tired of WordPress because I’ve
    had issues with hackers and I’m looking at alternatives for another platform.
    I would be great if you could point me in the
    direction of a good platform.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s