-
Notifications
You must be signed in to change notification settings - Fork 76
ObservableObject
Rico Suter edited this page Jun 10, 2015
·
10 revisions
- 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.
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.
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; }
}
}