Improved OnPropertyChanged() in .NET 4.5

9:42 PM




Well, we all know (who is programming in WPF) the may be one of the most recently used in WPF,   OnPropertyChanged() method.

In general we use this approach to notify data GUI, that data it bind to has been changed.

Usually it will look something very similar to following:


class MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
 
    private string title;
    public string Title
    {
        get { return title; }
        set
        {
            title = value;
            OnPropertyChanged("Title");
        }
    }
 
    private void OnPropertyChanged(string propName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}


Our solution based on CallerMemberName which allows to obtain the method or property name of the caller to the method. Here is the reference to MSDN.

But there is issue with such form: We pass a string, which means that if in the future property name will be changed, and we could forget to change string parameter inside i.e. OnPropertyChanged("stillOldValue"), will probably affect on changes inside our WPF application.

Therefore we have a nice solution:


private void OnPropertyChanged([CallerMemberName]string propName = null)
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
}


public string Title
{
    get { return title; }
    set
    {
        title = value;
        OnPropertyChanged();
    }
}

P.S.
All credits to Shlomo Goldberg :)

You Might Also Like

0 comments.

Popular Posts

Google+ Followers

Total Pageviews