【问题标题】:Static property using INotifyPropertyChanged. C#使用 INotifyPropertyChanged 的​​静态属性。 C#
【发布时间】: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(...) 是当前最新的写法。你应该这样做。

标签: c# wpf


【解决方案1】:

只需传递null 而不是this

public static event PropertyChangedEventHandler StaticPropertyChanged;

private static void NotifyStaticPropertyChanged([CallerMemberName] string name = null)
{
    StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(name));
}

有关静态属性更改通知的详细信息,请参阅this blog post

【讨论】:

  • 也感谢您的链接,这对我帮助很大。
  • 好的,我遇到了一个问题,您的链接没有显示如何使用 Static MemberStaticPropertyChanged。这会在 XAML 中引发错误,指出无法解析。不幸的是,链接没有涉及到这一点,有什么想法吗?
  • 不确定你的意思。该帖子还展示了如何绑定到静态属性。可能会问一个新的 StackOverflow 问题并提供错误的详细信息。
  • 对不起,我的意思是在它显示的链接中 Two Approaches to Change Notification ,它只显示了如何绑定第一种方法来绑定静态属性。我正在使用第二种方法,据我所知,链接没有显示如何执行此操作。还是我错过了什么?干杯
  • 这只是实现静态属性更改通知的两种方法。两者绑定到这样的静态属性是相同的。
猜你喜欢
  • 2013-01-14
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多