Sina Iravanian

I blog about software development

Handy Extensions for INotifyPropertyChanged

| Comments

I recently created a library that contains some handy extensions for INotifyPropertyChanged interface (aka INPC). To start using the library, add the following to the top of your C# code:

1
using NotifyPropertyChangedExtensions;

How to easily raise INPC in a refactor friendly way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MyClass : INotifyPropertyChanged
{
    private int _number;

    public int Number
    {
        get { return _number; }
        set
        {
            if(_number != value)
            {
                _number = value;
                this.RaisePropertyChanged(() => Number);
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

How to easily handle (listen to) INPC in a refactor friendly way

1
2
3
4
5
6
MyClass myObject = ...;

myObject.HandleOnPropertyChanged(src => src.Number, sender =>
    {
        Console.WriteLine("Number changed to {0}", sender.Number);
    });

How to do one-way binding from a class that implements INPC

1
2
3
4
5
6
7
var source = new MyClass();
var target = new TargetClass();

source.BindProperty(src => src.Number, target, t => t.Num);

source.Number = 10;
Console.WriteLine(target.Num); // 10

You can negate a boolean property while binding it. I use it a lot and find it very handy.

1
2
3
4
source.BindProperty(src => src.IsActive, target, t => !t.IsDeleted);

source.IsActive = false;
Console.WriteLine(target.IsDeleted); // True

You can bind primitive data-types in source class to Nullable primitive data-types in the target class, and vice versa.

1
source.BindProperty(src => src.Number, target, t => t.NullableNumber);

What happens if source is null, and the target is not Nullable?

The default behavior is to update target with default value of that type:

1
2
3
4
5
target.Number = 10;
source.BindProperty(src => src.NullableNumber, target, t => t.Number);

source.NullableNumber = null;
Console.WriteLine(target.Number); // 0

You can also choose not to update target if source becomes null:

1
2
3
4
5
6
target.Number = 10;
source.BindProperty(src => src.NullableNumber, target, t => t.Number,
    BindPropertyOptions.DontUpdateWhenSourceIsNullAndTargetIsNotNullable);

source.NullableNumber = null;
Console.WriteLine(target.Number); // still 10

How to find more information about this library?

At the moment the best way to find out how this library works is by reading the unit tests or at least their titles.

INPC-Extensions is now hosted in GitHub and is licensed under MIT.

Comments