Search code examples
c#wpfmvvm-light

MVVM Light - How to detect if some property has changed


How can I detect if some property has changed, but I don't want to subscribe PropertyChanged event. I want to set HasChanges before PropertyChanged event is raised.

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

My project type is: WPF App (.NET Framework 4.6)


Solution

  • You can override the RaisePropertyChanged method from ViewModelBase class, since it's virtual, according to source code, and set HasChanges property in this method. If you want to track changes before PropertyChanged actually, use the PropertyChanging event, it's raised before property is set to new value in a Set method, according to the sources again

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