Search code examples
mvvminotifypropertychanged

MVVM - PropertyChangedEventHandler


I am starting with MVVM.

My application uses this "pattern (PM pattern - let's not debate this here :) )"and works fine; The project is very simple and supposedly easy for beginners to get to grips with!! If only it was... :)

There is one thing which is puzzling me, which may have nothing to do with MVVM per se; the PropertyChangedEventHandler.

I am stepping through my code, line by line and can see the call (code below) but I'm not sure why I am calling this handler or what it is doing!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Input;

namespace drMVVM.Model
{
    public class TextContent : INotifyPropertyChanged
    {
        private string text;
        public string Text
        {
            get { return text; }
            set
            {
                if (text != value)
                {
                    text = value;
                    OnPropertyChanged("Text");
                }
            }
        }

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

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}

I also have a similar layout of code for my viewmodel, but instead of setting the properties, I'm just creating an instance of the object and applying any additional logic.

Is the PropertyChangedEventArgs used to update just the properties of the model that something has changed? If so, why is it implemented in the model class and not just the ModelView? Is it because it can instinctively know whether to just listen for a change or to provide details a notification that a change occurs? If it's a notification (I assume so hence the name of the interface) then what am I notifying in my Model class?


Solution

  • INotifyPropertyChanged is required whenever you want to notify someone about changes of your properties. So if your ViewModel needs to notify the view about changes so the view updates its data binding, then you ViewModel needs to implement it and raise the event with every change of the properties.

    Similar, if your model has properties that can change and you want to be notified about, then implement it in your model as well.

    It’s not really necessary for something, unless there are automated implications for it; one being the data binding in WPF which needs a hint so it knows that it has to update.