MVVM Light - 如何检测某些 属性 是否已更改

MVVM Light - How to detect if some property has changed

如何检测某些 属性 是否已更改,但我不想订阅 PropertyChanged 事件。我想在引发 PropertyChanged 事件之前设置 HasChanges

public class PatientVM : ViewModelBase
{
    private readonly PatientEntity _entity;

    public int Id
    {
        get => _entity.Id;
        set => Set(ref _entity.Id, value);
    }

    public string Name
    {
        get => _entity.Name;
        set => Set(ref _entity.Name, value);
    }

    public bool HasChanges { get; set; }
}

我的项目类型是:WPF App (.NET Framework 4.6)

您可以覆盖 ViewModelBase class 中的 RaisePropertyChanged 方法,因为它是虚拟的,根据 source code,并设置 HasChanges 属性 在这个方法中。如果你想跟踪 PropertyChanged 之前的变化,使用 PropertyChanging 事件,它在 属性 被设置为 Set 方法中的新值之前引发,再次根据消息来源

#if !PORTABLE && !SL4
    RaisePropertyChanging(propertyName);
#endif
    field = newValue;
    // ReSharper disable ExplicitCallerInfoArgument
    RaisePropertyChanged(propertyName);
    // ReSharper restore ExplicitCallerInfoArgument

您可以简单地订阅在 ViewModelBase 基础 class 中实现的 PropertyChanging 事件。

public PatientVm()
{
    PropertyChanging += (e => HasChanges = true);
}