0

In most tuts they say to write method like this:

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

and call it such as OnPropertyChanged("PropName");. But this seems to be very static and unable to refactor automatically. Is there a way to do this more dynamically? I considered using System.Diagnostic.StackTrace class to get the name of property, but it looks ugly and not much efficiently, and moreover I can't access it in for instance Windows Phone 8 app (why!?).

pt12lol
  • 2,332
  • 1
  • 22
  • 48

2 Answers2

1

You can use the [CallerMemberName] if you are using .NET Framework 4.5

so your code will be :

using System.Runtime.CompilerServices;

class BetterClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    // Check the attribute in the following line :
    private void FirePropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private int sampleIntField;

    public int SampleIntProperty
    {
        get { return sampleIntField; }
        set
        {
            if (value != sampleIntField)
            {
                sampleIntField = value;
                // no "magic string" in the following line :
                FirePropertyChanged();
            }
        }
    }
}

as described in the question INotifyPropertyChanged : is [CallerMemberName] slow compared to alternatives?

Community
  • 1
  • 1
Yahya
  • 501
  • 4
  • 8
0

Caliburn.micro has a PropertyChangeBase that allows you to use lambdas. You can inherit from it and call the base method. For a property Name you can do this:

NotifyOfPropertyChange(() => Name);

With C# 6.0 you can implement your own base class and use the nameof operator, which will help with refactoring:

OnPropertyChanged(nameof(Name));
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
  • 1
    [SharpObservation](https://sharpobservation.codeplex.com/) and [MVVM Light Toolkit](https://mvvmlight.codeplex.com/) have these base-classes as well :) –  Feb 20 '15 at 11:35