【发布时间】:2017-05-22 00:34:36
【问题描述】:
我正在尝试创建一个静态属性,其中INotifyPropertyChanged 将更新对我绑定到的DataGrid ComboBox 所做的任何更改。
我收到此错误,
错误 CS0026 关键字“this”在静态属性中无效,静态 方法或静态字段
通过搜索我找到了这个Why can't you use the keyword 'this' in a static method in .Net?,但即使在经历了所有之后我仍然无法弄清楚如何让它工作。
但是,我所做的任何更改只会否定我正在尝试使用 INotifyPropertyChanged 制作静态属性???
我的代码:
private static List<string> _nursingHomeSectionListProperty;
public static List<string> NursingHomeSectionListProperty
{
get { return _nursingHomeSectionListProperty; }
set
{
_nursingHomeSectionListProperty = value;
NotifyStaticPropertyChanged();
}
}
并且属性改变了处理程序
public static event PropertyChangedEventHandler StaticPropertyChanged;
public static void NotifyStaticPropertyChanged([CallerMemberName] string propertyName = null)
{
StaticPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
下面的代码是我如何将属性更改处理程序用于非静态属性,
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
【问题讨论】:
-
我不明白为什么你的模型需要静态属性,但
Invoke的第一个参数是发送者。一个简单的new object()就可以了 -
另外,你为什么使用委托。调用并命名你的 raise 方法 Notify... 而不是 On?
-
@Sefe 因为
?.运算符。方法的名称无关紧要。 -
不要使用?。在这些情况下。诉诸 Invoke 是对这个运算符的过度使用。
-
@Sefe 我猜你不知道
?.是什么。写PropertyChanged?.Invoke(...)是当前最新的写法。你应该这样做。