是否可以触发 OnPropertyChanged 事件而不在 ViewModel 的 属性 的 setter 中显式调用它?

Is it possible to fire the OnPropertyChanged Event without explictly calling it in the setter of a property on ViewModel?

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

是否可以编写一个自动执行的基本 ViewModel,可能会在 属性 值更改时传递 nameof(属性)?

提前致谢。

Fody 允许您使用属性连接 INotifyPropertyChanged 而不必在每个 setter.

中显式调用它
[ImplementPropertyChanged]
public class Person 
{        
    public string GivenNames { get; set; }
    public string FamilyName { get; set; }
}

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

如果您愿意编写 代码,您可以将其放入您的基础 class(C#6 for ?. 并且您需要 System.Runtime.CompilerServices 对于 CallerMemberName):

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

所以在你的 属性 setter 中,你只是把

set
{
   backingField = value;
   OnPropertyChanged();
}