Uncategorized

[WPF] INotifyPropertyChanged

This interface contains PropertyChanged event which will notify client when a property value changes. Normally, this interface should be implemented on all ViewModel in WPF, but to reduce code repetition and maintainability, we will implement a ViewModelBaseClass instead to implement that interface, then let the ViewModel inherit from that base class.

public class ViewModelBase : INotifyPropertyChanged
    {
        protected virtual void SetProperty(ref T member, T val,
            [CallerMemberName] string propertyName = null)
        {
            if (object.Equals(member, val)) return;
 
            member = val;
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
 
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged = delegate { };
    }

Example:

private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                SetProperty(ref _name, value);
            }
        }

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