0

I've looked around a bit online and wasn't able to easily find a solution to what i was looking for. It may be in part to me not being sure the terminology to search for.

I wanted to know is there a way to call the PropertyChanged event using the property member name like so...

    private string height;
    public string Height
    {
        get { return name; }
        set
        {
            Set(ref height, value);
            RaisePropertyChanged( ()=> Name);
        }
    }

rather than using the actual string which can be seen here..

    private string height;
    public string Height
    {
        get { return name; }
        set
        {
            Set(ref height, value);
            RaisePropertyChanged("Name");
        }
    }

Raise Event

protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

I've attempted a solution to this, but wasn't able to come to a conclusion. I know there are methods out there somewhere and im sure there are more modern ways to do this. Its 2016!!

Douglas
  • 53,759
  • 13
  • 140
  • 188
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

1 Answers1

3

Since you appear to be using C# 6, you can use the nameof operator, which resolves the name of the referenced property at compile time, passing a string to your method.

RaisePropertyChanged(nameof(Name));

If you need to use an earlier C# compiler, you can resolve the name of the property through a lambda expression; this is what Entity Framework does for its Include operator. You can define a GetPropertyName utility method (see example), then call it like so:

RaisePropertyChanged(GetPropertyName(() => Name));
Community
  • 1
  • 1
Douglas
  • 53,759
  • 13
  • 140
  • 188