当属性必须引发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#可能性,是否有一种方法可以简化原始代码?(我正在把范围扩大到任何可能性)。
https://stackoverflow.com/questions/58184599
复制相似问题