Skip to content

PropertyChanged

Håvard Moås edited this page Apr 1, 2020 · 5 revisions

Notifying property changed is a common scenario when working with Xamarin.Forms and the MVVM-pattern. We do not want our consumers to have to inherit from a base class to notify when property changed. We provide an extension based solution for our consumers.

A view model normally implement INotifyPropertyChanged. With our API you only need to implement the PropertyChangedEventHandler.

👉 The PropertyChangedEventHandler is called PropertyChanged in our examples.

Raise property changed for a property

Outside of a property

public void DoSomething()
{
    ...
    this.OnPropertyChanged(nameof(MyProperty), PropertyChanged);
    //or
    PropertyChanged.Raise(nameof(MyProperty));
    ...
}

Inside of a property

public string MyProperty
{
    get => m_myBackingStore;
    set 
    {
        ...
        this.OnPropertyChanged(PropertyChanged);
        //or
        PropertyChanged.Raise();
        ...
    }
}

Raise on property changed after setting a value to a backing store

public string MyProperty
{
    get => m_myBackingStore;
    set 
    {
        ...
        this.Set(ref m_myBackingStore, value, PropertyChanged);
        //or
        PropertyChanged.RaiseWhenSet(ref m_myBackingStore, value);
        ...
    }
}

👉 Set() and RaiseAfter() returns a boolean value indicating if the value was set or not.

Raise multiple property changes

public void DoSomething()
{
    ...
    this.OnMultiplePropertiesChanged(
        nameof(MyProperty), 
        nameof(MySecondProperty),
        nameof(MyThirdProperty),
        PropertyChanged);
    //or
    PropertyChanged.RaiseForEach(
        nameof(MyProperty),
        nameof(MySecondProperty),
        nameof(MyThirdProperty));
    ...
}

Other samples can be found here.

Clone this wiki locally