How to raise PropertyChanged event without using string name

后端 未结 8 1332
后悔当初
后悔当初 2020-11-29 00:22

It would be good to have ability to raise \'PropertyChanged\' event without explicit specifying the name of changed property. I would like to do something like this:

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 01:11

    I´m using the extension method

    public static class ExpressionExtensions {
        public static string PropertyName(this Expression> projection) {
            var memberExpression = (MemberExpression)projection.Body;
    
            return memberExpression.Member.Name;
        }
    }
    

    in combination with the following method. The method is defined in the class that implements the INotifyPropertyChanged interface (Normally a base class from which my other classes are derived).

    protected void OnPropertyChanged(Expression> projection) {
        var e = new PropertyChangedEventArgs(projection.PropertyName());
    
        OnPropertyChanged(e);
    }
    

    Then i can raise the PropertyChanged-Event as follows

    private double _rate;
    public double Rate {
            get {
                return _rate;
            }
            set {
                if (_rate != value) {
                  _rate = value;                     
                  OnPropertyChanged(() => Rate );
                }
            }
        }
    

    Using this approach, its easy to rename Properties (in Visual Studio), cause it ensures that the corresponding PropertyChanged call is updated too.

提交回复
热议问题