6 comments

  1. I thought you could make an even more elegant solution to this by implementing both NotifyPropertyChanged and OnPropertyChanged as extension methods on the INotifyPropertyChanged interface. That way you wouldn’t have to inherit from a base class. But the problem is that from the extension methods you do not have access to the PropertyChangedEvent. It is on the interface, but you cannot get the underlying PropertyChangedEventHandler delegate instance.

    Jonathan Mezach

  2. You can create an extension method on PropertyChangedEventHandler and raise the event using something like this:
    PropertyChanged.Raise(this, () => this.Name);

    Extension method

    ///

    /// Contains extension methods for the PropertyChangedEventHandler delegate
    ///

    static class PropertyChangedEventHandlerExtensions
    {
    ///

    /// Extension method that raises the PropertyChanged event
    ///

    /// The type of the property that changed
    /// The PropertyChanged event
    /// The object of which the property changed
    /// /// Expression tree of the property that changed
    /// e.g. ‘() => this.PropertyName’
    ///
    public static void Raise(this PropertyChangedEventHandler handler
    , object sender, Expression> property)
    {
    PropertyChangedEventHandler temp = handler;

    if (temp != null)
    {
    MemberExpression me = property.Body as MemberExpression;
    if (me != null)
    {
    temp(sender, new PropertyChangedEventArgs(me.Member.Name));
    }
    }
    }
    }

    Ronald Bosma

  3. Indeed, in extension methods you do not have access to private fields. And that is good; if it was possible to access these you would be able to write code that depends on class internal thereby breaking encapsulation.

    Erno de Weerd

  4. Indeed that is possible. What I dislike about this is that the extension does not stick to the regular pattern of providing a protected method that raises the event. But it is a nice idea. Thanks!

    Erno de Weerd

  5. Would it not be more correct in this implementation to also make the ‘general’ OnPropertyChanged method private? Or is this just a way to leave it open to enable a refresh of all properties by parsing an empty string as property name?

    Just a thought.

    Meile Zetstra

  6. Meile,
    The reason for making it protected (as with any event raiser) is to enable deriving classes to use this method to raise the event when needed. Making it private would make that impossible.
    As for raising a general PropertyCanged event with an empty string; although it is possible it is not according to the specs I guess.

    Erno de Weerd

Comments are closed.