gpt4 book ai didi

c# - NotifyOnPropertyChange实现

转载 作者:行者123 更新时间:2023-12-03 10:23:03 25 4
gpt4 key购买 nike

如何实现NotifyOnPropertyChange方法?从继承者ViewModelBase调用它可以是:

NotifyOnPropertyChange (() => Property) 

该方法的输入将应用lambda表达式,该表达式指定需要通知的更改属性。

最佳答案

您的实现如下所示。它是使用System.Linq.Expressions命名空间实现的。

        protected void RaisePropertyChanged<T>(System.Linq.Expressions.Expression<Func<T>> lambda)
{
dynamic l = lambda.Body;
string propertyName = l.Member.Name;
OnPropertyChanged(propertyName);
}

这是全类的一个例子。
    public class NotificationObject : INotifyPropertyChanged
{
private string _someProperty;

public string SomeProperty
{
get { return _someProperty; }
set
{
_country = value;
RaisePropertyChanged(() => SomeProperty);
}
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}



protected void RaisePropertyChanged<T>(System.Linq.Expressions.Expression<Func<T>> lambda)
{
dynamic l = lambda.Body;
string propertyName = l.Member.Name;
OnPropertyChanged(propertyName);
}
}

不使用动态功能的完整实现如下所示:
        protected void RaisePropertyChanged<T>(System.Linq.Expressions.Expression<Func<T>> lambda)
{
if (lambda == null) throw new ArgumentNullException("lambda");

var memberExpression = lambda.Body as MemberExpression;
if (memberExpression == null) throw new ArgumentException("Invalid lambda expression.","lambda");

var property = memberExpression.Member as PropertyInfo;
if (property == null) throw new ArgumentException("Invalid lambda expression. Expression must be a property.", "lambda");

// check if the property is not static
var getMethod = property.GetGetMethod(true);
if (getMethod.IsStatic) throw new ArgumentException("Invalid lambda expression. Property cannot be static.", "propertyExpression");

string propertyName = memberExpression.Member.Name;
OnPropertyChanged(propertyName);
}

关于c# - NotifyOnPropertyChange实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23938991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com