This project is read-only.

The page has been moved to GitHub

ObservableObject

Package: MyToolkit
Platforms: All (PCL)

Subclasses: 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.

Usage

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.

Property changed event for dependent 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

Notes

Last edited Jun 3, 2015 at 10:53 PM by rsuter, version 34