C# 如何在静态属性(Caliburn Micro)中使用NotifyOfPropertyChange 为什么我不能在静态属性中使用NotifyOfPropertyChange
caliburn micro中是否有另一个NotifyOfPropertyChange函数可以用于静态属性或其他使用方法,以及如何使用C# 如何在静态属性(Caliburn Micro)中使用NotifyOfPropertyChange 为什么我不能在静态属性中使用NotifyOfPropertyChange,c#,wpf,mvvm,caliburn.micro,C#,Wpf,Mvvm,Caliburn.micro,caliburn micro中是否有另一个NotifyOfPropertyChange函数可以用于静态属性或其他使用方法,以及如何使用 private static string _data = ""; public static string _Data { get { return _data; } set { _data = value; NotifyOfPropertyChange(() =>
private static string _data = "";
public static string _Data
{
get
{
return _data;
}
set
{
_data = value;
NotifyOfPropertyChange(() => _Data);
}
}
您可以创建自己的方法来引发
StaticPropertyChanged
事件:
private static string _data = "";
public static string _Data
{
get
{
return _data;
}
set
{
_data = value;
NotifyStaticPropertyChanged(nameof(_Data));
}
}
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
private static void NotifyStaticPropertyChanged(string propertyName)
{
if (StaticPropertyChanged != null)
StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
私有静态字符串_data=”“;
公共静态字符串\u数据
{
得到
{
返回数据;
}
设置
{
_数据=价值;
NotifyStaticPropertyChanged(名称(_数据));
}
}
公共静态事件EventHandler StaticPropertyChanged;
私有静态void NotifyStaticPropertyChanged(字符串propertyName)
{
if(StaticPropertyChanged!=null)
StaticPropertyChanged(空,新PropertyChangedEventArgs(propertyName));
}
有关更多信息,请参阅以下博文:
为什么我不能在静态属性中使用NotifyOfPropertyChange
您不能像现在这样使用它,因为NotifyOfPropertyChange
是一个实例方法,而不是静态方法
caliburn micro[…]中是否还有另一个NotifyOfPropertyChange函数
不,据我所知,不是。但是,您可以推出自己的实现,例如
public static event PropertyChangedEventHandler PropertyChanged;
private static void NotifyPropertyChange<T>(Expression<Func<T>> property)
{
string propertyName = (((MemberExpression) property.Body).Member as PropertyInfo).Name;
PropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
}
在属性设置器中
关于签名的编辑: 而不是
private static void NotifyPropertyChange<T>(Expression<Func<T>> property) { ... }
它的优点是不需要显式地传递任何内容,您可以这样调用它
NotifyOfPropertyChange(() => _Data);
NotifyPropertyChange();
因为编译器将自动更改属性名
我选择了Expression
,因为调用(几乎)与caliburn micro的NotifyPropertyChange
完全相同
但是,您需要知道的是,由于
NotifyPropertyChange
方法是静态的而不是实例方法,因此您无法像使用实例方法一样将其重构为基类(例如MyViewModelBase
),这也是caliburn micro所做的
因此,您需要在每个具有静态属性的ViewModel中复制并粘贴事件和
NotifyPropertyChange
方法,或者创建一个静态帮助器来包装功能。太好了!帮助很大:)Thanks@FrancisCanoza很高兴听到这有帮助。另外,请参阅我对NotifyPropertyChange
方法的签名所做的编辑。您可以使用任何想要使用的签名。nameof(\u Data)
应该是这样的字符串类型NotifyStaticPropertyChanged(\u Data”)代码>:)感谢您的帮助:D操作符的名称是在C#6中引入的:这给了我很多启示:D我应该正确使用nameof
而不是字符串:)
NotifyPropertyChange();