Skip to content

Bindable

Niclas Kristek edited this page Jul 9, 2019 · 5 revisions

The Bindable abstract class provides a base implementation for the INotifyPropertyChanging and INotifyPropertyChanged interfaces.

It includes SetProperty<T> methods to set the value of a property to the respective backing field. If the value is different, the NotifyPropertyChanging method is called before and the NotifyPropertyChanged method is called after the storage is set. To compare the old value to the given value, the default comparer is used. If you need to use a different comparer, set the optional comparer parameter to a value different than null. The propertyName parameter has the CallerMemberNameAttribute. When calling the SetProperty<T> method from inside the property setter, the parameter automatically gets populated with the correct name. If changing the value of a specific property requires the reevaluation of all other properties, the propertyName parameter should be explicitly set to null or an empty string.

If you need to manually raise events on the PropertyChanging or PropertyChanged event handlers, it's recommended to use the NotifyPropertyChanging or NotifyPropertyChanged methods.

private object _myProperty;

public object MyProperty
{
    get => _myProperty;
    set => SetProperty(ref _myProperty, value);
}

If the old value of the property is needed, use the overload with the out parameter:

private object _myProperty;

public object MyProperty
{
    get => _myProperty;
    set
    {
        if (SetProperty(ref _myProperty, value, out var oldValue)
        {
            // will only be executed if the value was different to the old value
        }
    }
}

There is also an overload which accepts a storage field of type WeakReference<T>. To simplify the getter, an extension method for WeakReference<T> can be used:

private WeakReference<object> _myWeakProperty;

public object MyWeakProperty
{
    get => _myWeakProperty?.TargetOrDefault();
    set => SetProperty(ref _myWeakProperty, value);
}
Clone this wiki locally