是否可以触发 OnPropertyChanged 事件,而无需在 ViewModel 上的属性的 setter 中显式调



在我的场景中,每次更改属性时,我都想触发 OnPropertyChanged 事件

是否可以编写一个自动执行的基本视图模型,也许在属性值更改时传递 nameof(属性)?

提前谢谢。

是否可以在不编写代码的情况下触发PropertyChanged事件?的,尽管您必须使用注入名为Fody的调用的第三方库。您可以在以下位置找到它: https://github.com/Fody/PropertyChanged

如果你愿意写一点代码,你可以把它放在你的基类中(C#6 for ?. 你需要System.Runtime.CompilerServicesforCallerMemberName):

protected void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventargs(propertyName));
}

所以在你的财产设置器中,你只是把

set
{
backingField = value;
OnPropertyChanged();
}

Fody 允许你使用属性来连接 INotifyPropertyChanged,而不必在每个 setter 中显式调用它。

[ImplementPropertyChanged]
public class Person 
{        
public string GivenNames { get; set; }
public string FamilyName { get; set; }
}

最新更新