INotifyPropertyChanged + dynamic = NotifiableExpandoObject

IMPORTANT NOTE: this code won’t work with WPF. Send me a patch :)

I just make a proof of concept with dynamics, and this is the result.

[TestMethod]
public void should_work()
{
    dynamic obj = new MyNotifiableExpandoObject();
    bool wasRaised = false;

    ((INotifyPropertyChanged)obj).PropertyChanged 
        += (sender, arg) => 
        {
            wasRaised = true;
            arg.PropertyName.Should().Be.EqualTo("Name");
        };

    obj.Name = "José";
    wasRaised.Should().Be.True;
}
 

I'm using C# 4 and the new keyword dynamic, MyNotifiableExpandoObject is a class that inherits from this one, first I tried to use ExpandoObject but.. is sealed.

So, my notifiable expando object is as follows:

public class MyNotifiableExpandoObject  : MyExpando, INotifyPropertyChanged
{
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler eventHandler = PropertyChanged;
        if (eventHandler != null) eventHandler(this, new PropertyChangedEventArgs(propertyName));
    }

    public override bool  TrySetMember(SetMemberBinder binder, object value)
    {
        var result = base.TrySetMember(binder, value);
        OnPropertyChanged(binder.Name);
        return result;
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler  PropertyChanged;

    #endregion
}

I hope you like it. Now ever property you set the propertychanged event will be raised properly.


blog comments powered by Disqus
  • Categories

  • Archives