【问题标题】:Is it possible to declare a property raising PropertyChanged event using a syntax similar to an auto-property ({ get; set; })?是否可以使用类似于自动属性 ​​({ get; set; }) 的语法来声明引发 PropertyChanged 事件的属性?
【发布时间】:2019-10-01 12:16:03
【问题描述】:

我想知道在必须引发PropertyChanged 事件时如何简化属性的使用。我的意思是,只要您需要引发事件,setter 就必须这样做,因此该属性不能是自动属性。这会导致代码变得复杂,尤其是当涉及多个属性时,除了简单地引发事件之外别无其他目的:

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));
}

复杂性在于每个属性都重复的这部分:

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

因为不可能这样表达:

public FlowDocument Document { get; setAndRaiseEvent; }

在网站上的搜索提出了这个类似但不重复的问题:

对于当前的 C# 可能性,有没有办法简化原始代码? (我将范围扩大到任何可能性)。

【问题讨论】:

  • 不使用 AOP(如PostSharpFody 或其他),没有。您可以使用反射发射在运行时生成代码,如果您正确执行,这可能会起作用,但在 C# 语言中没有开箱即用的东西,没有。

标签: c# properties inotifypropertychanged


【解决方案1】:

“使用当前的 C# 可能性”?没有。

但如果你安装了FodyPropertyChanged.Fody NuGet 包,并在你的项目中添加了一个名为“FodyWeavers.xml”的文件,内容如下:

<Weavers>
    <PropertyChanged />
</Weavers>

...Fody 将在您构建项目时将引发PropertyChanged 事件的代码注入到所有实现INotifyPropertyChanged 的类的所有属性设置器中。

更多信息请参考GitHub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 2023-03-16
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多