Skip to content

ObservableObject

Rico Suter edited this page Jun 10, 2015 · 10 revisions

Class which implements INotifyPropertyChanged (INPC). If your object needs bindable properties or property changed events, simply inherit from ObservableObject and implement the properties as shown below.

Implementation of an observable property

With the following property implementations any refactorings will work properly.

Implementation with C# 5.0 (recommended):

public class MyViewModel : ObservableObject
{
    private int _myProperty;
    public int MyProperty 
    {
        get { return _myProperty; }
        set { Set(ref _myProperty, value);
    }
}

Old way (before C# 5.0, not recommended):

public class MyViewModel : ObservableObject
{
    private int _myProperty;
    public int MyProperty 
    {
        get { return _myProperty; }
        set { Set(() => MyProperty, ref _myProperty, value);
    }
}

Defining the property name as string is also possible but not recommended as it causes problems when refactoring. The performance impact of using lambdas versus strings is very small.

Dependent or derived properties

The following code shows how to update/raise a changed event for a dependent property:

public class MyViewModel : ObservableObject
{
    private int _myProperty;
    public int MyProperty 
    {
        get { return _myProperty; }
        set 
        { 
            if (Set(ref _myProperty, value))
                RaisePropertyChanged(() => DependentProperty);
        }
    }

    public int DependentProperty
    {
        get { return MyProperty * 2; }
    }
}

Source code

Clone this wiki locally