简体   繁体   English

是否可以使用类似于自动属性 ({ get; set; }) 的语法来声明引发 PropertyChanged 事件的属性?

[英]Is it possible to declare a property raising PropertyChanged event using a syntax similar to an auto-property ({ get; set; })?

I'm wondering how to simplify the use of properties when they must raise the PropertyChanged event.我想知道在必须引发PropertyChanged事件时如何简化属性的使用。 I mean as soon as you need to raise the event, the setter must do it, hence the property cannot be an auto-property.我的意思是,一旦您需要引发事件,setter 就必须这样做,因此该属性不能是自动属性。 This causes some complication of the code, especially when there are multiple properties concerned, for no other purpose than to simply raise the event:这会导致代码的一些复杂性,特别是当涉及多个属性时,除了简单地引发事件之外没有其他目的:

protected FlowDocument document;
protected bool hyphenation = true;
protected bool optimalParagraphs = true;

public event PropertyChangedEventHandler PropertyChanged;

public FlowDocument Document { get => document; set { document = value; RaisePropertyChanged (); } }
public bool Hyphenation { get => hyphenation; set { hyphenation = value; RaisePropertyChanged (); } }
public bool OptimalParagraphs { get => optimalParagraphs; set { optimalParagraphs = value; RaisePropertyChanged (); } }

// Raise event
protected void RaisePropertyChanged ([CallerMemberName] string propertyName = null) {
    PropertyChanged?.Invoke (this, new PropertyChangedEventArgs (propertyName));
}

The complication is within this part which is repeated for each property:复杂性在这部分中,每个属性都重复:

protected FlowDocument document;
public FlowDocument Document { get => document; set { document = value; RaisePropertyChanged (); } }

because there is no possibility to express it like:因为不可能像这样表达它:

public FlowDocument Document { get; setAndRaiseEvent; }

A search on the site proposes this similar, but not duplicate, question:该网站上的搜索提出了这个类似但不重复的问题:

With current C# possibilities, is there a way to simplify the original code?使用当前的 C# 可能性,有没有办法简化原始代码? (I'm enlarging the scope to any possibility). (我将 scope 扩大到任何可能性)。

"With current C# possibilities"? “与当前的 C# 可能性”? No.不。

But if you install the Fody and PropertyChanged.Fody NuGet packages and add a file named "FodyWeavers.xml" with the following contents to your project:但是,如果您安装了FodyPropertyChanged.Fody NuGet 软件包,并在您的项目中添加了一个名为“FodyWeavers.xml”的文件,其内容如下:

<Weavers>
    <PropertyChanged />
</Weavers>

... Fody will inject code that raises the PropertyChanged event into all property setters of all classes that implement INotifyPropertyChanged when you build the project. ... Fody将在构建项目时将引发PropertyChanged事件的代码注入到所有实现INotifyPropertyChanged的类的所有属性设置器中。

Please refer to GitHub for more information.更多信息请参考GitHub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM