José F. Romaniello

Las aventuras y desventuras de un codificador.

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.

| More

4 comentarios:

Can WPF actually bind to this?  Can it actually find the members?

José F. Romaniello dijo...

At first glance, WPF cannot find the members, need more investigation.

Now ExpandoObject implements INotifyPropertyChanged

José F. Romaniello dijo...

<span style="color: #808080;">Cool! thank you for the tip!</span>
Is this part of the .net 4 beta2?
Because in beta 1, it doesn't.

Publicar un comentario