Skip to content

MVVM PropertyChanged

Jan M edited this page Aug 12, 2020 · 2 revisions

The BindingBase is our default INotifyPropertyChanged implementation, both our ModelBase and ViewModelBase rely on it.

Features:

  • implementation of INofityPropertyChanged
  • convenient methods GetValue and SetValue to easily declare a property and make use of INotifyPropertyChanged
  • INotifyPropertyChanged for nested classes
  • INotifyPropertyChanged for dependent properties (e.g. update message for Age property when DateOfBirth has changed)
  • controlling the INotifyPropertyChanged events via attribute
  • automatically updating ICommand.CanExecute if there is any ICommand property in the class (see: Options)

How to declare a property the CodeMonkeys-way

public class Model :
    BindingBase
{
    // simple property with PropertyChanged support
    public string Name
    {
        get => return GetValue<string>();
        set => SetValue(value);
    }

    // property with default value
    public Guid ID
    {
        get => return GetValue(Guid.NewGuid());
        set => SetValue(value);
    }

    // add custom PropertyChanged handler
    public DateTime DateOfBirth
    {
        get => return GetValue<DateTime>();
        set => SetValue(value, OnDateOfBirthChanged);
    }
    private void OnDateOfBirthChanged (object sender, PropertyChangedEventArgs eventArgs) { ... }

    // add custom PropertyChanged handler
    // and custom PropertyChanging handler
    public int ZipCode
    {
        get => return GetValue<int >();
        set => SetValue(value, OnZipCodeChanged, OnZipCodeChanging);
    }
    private void OnZipCodeChanged(object sender, PropertyChangedEventArgs eventArgs) { ... }
    private void OnZipCodeChanging(object sender, PropertyChangingEventArgs eventArgs) { ... }

    // add custom PropertyChanged action
    public string Url
    {
        get => return GetValue<string>();
        set => SetValue(value, (url) => 
            {
                if (!url.EndsWith('/'))
                    url += "/";
            });
    }
}

Options

bool UseCommandRelevanceAttribute

Toggles whether ICommand.CanExecuteChanged should be invoked automatically on every PropertyChanged (false) event or only when a specific property has changed (true).
Default value is true.

Clone this wiki locally