Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better PropertyChanged and PropertyChanging event handling

Tags:

c#

.net

c#-4.0

I am implementing the observer pattern for our application - currently playing around with the RX Framework.

I currently have an example that looks like this:

Observable.FromEventPattern<PropertyChangedEventArgs>(Instance.Address, "PropertyChanged")
    .Where(e => e.EventArgs.PropertyName == "City")
    .ObserveOn(Scheduler.ThreadPool)
    .Subscribe(search => OnNewSearch(search.EventArgs));

(I have a similar one for "PropertyChanging")

The EventArgs don't give me much. What I would like is an extension of the EventArgs that would give me the ability to see the previous and new values, as well as the ability to mark the event in the 'changing' listener, such that the change wouldn't actually persist. How can this be done? Thanks.

like image 641
user981225 Avatar asked Dec 20 '11 14:12

user981225


2 Answers

I think that it comes down to how you implement the INotifyPropertyChanging and INotifyPropertyChanged interfaces.

The PropertyChangingEventArgs and PropertyChangedEventArgs classes unfortunately don't provide a before and after value of the property or the ability to cancel the change, but you can derive your own event args classes that do provide that functionality.

First, define the following event args classes. Notice that these derive from the PropertyChangingEventArgs class and PropertyChangedEventArgs class. This allows us to pass these objects as arguments to the PropertyChangingEventHandler and PropertyChangedEventHandler delegates.

class PropertyChangingCancelEventArgs : PropertyChangingEventArgs
{
    public bool Cancel { get; set; }

    public PropertyChangingCancelEventArgs(string propertyName)
        : base(propertyName)
    {
    }
}

class PropertyChangingCancelEventArgs<T> : PropertyChangingCancelEventArgs
{
    public T OriginalValue { get; private set; }

    public T NewValue { get; private set; }

    public PropertyChangingCancelEventArgs(string propertyName, T originalValue, T newValue)
        : base(propertyName)
    {
        this.OriginalValue = originalValue;
        this.NewValue = newValue;
    }
}

class PropertyChangedEventArgs<T> : PropertyChangedEventArgs
{
    public T PreviousValue { get; private set; }

    public T CurrentValue { get; private set; }

    public PropertyChangedEventArgs(string propertyName, T previousValue, T currentValue)
        : base(propertyName)
    {
        this.PreviousValue = previousValue;
        this.CurrentValue = currentValue;
    }
}

Next, you would need to use these classes in your implementation of the INotifyPropertyChanging and INotifyPropertyChanged interfaces. An example of an implementation is the following:

class Example : INotifyPropertyChanging, INotifyPropertyChanged
{
    public event PropertyChangingEventHandler PropertyChanging;

    public event PropertyChangedEventHandler PropertyChanged;

    protected bool OnPropertyChanging<T>(string propertyName, T originalValue, T newValue)
    {
        var handler = this.PropertyChanging;
        if (handler != null)
        {
            var args = new PropertyChangingCancelEventArgs<T>(propertyName, originalValue, newValue);
            handler(this, args);
            return !args.Cancel;
        }
        return true;
    }

    protected void OnPropertyChanged<T>(string propertyName, T previousValue, T currentValue)
    {
        var handler = this.PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs<T>(propertyName, previousValue, currentValue));
    }

    int _ExampleValue;

    public int ExampleValue
    {
        get { return _ExampleValue; }
        set
        {
            if (_ExampleValue != value)
            {
                if (this.OnPropertyChanging("ExampleValue", _ExampleValue, value))
                {
                    var previousValue = _ExampleValue;
                    _ExampleValue = value;
                    this.OnPropertyChanged("ExampleValue", previousValue, value);
                }
            }
        }
    }
}

Note, your event handlers for the PropertyChanging and PropertyChanged events will still need to take the original PropertyChangingEventArgs class and PropertyChangedEventArgs class as parameters, rather than a more specific version. However, you will be able to cast the event args objects to your more specific types in order to access the new properties.

Below is an example of event handlers for these events:

class Program
{
    static void Main(string[] args)
    {
        var exampleObject = new Example();

        exampleObject.PropertyChanging += new PropertyChangingEventHandler(exampleObject_PropertyChanging);
        exampleObject.PropertyChanged += new PropertyChangedEventHandler(exampleObject_PropertyChanged);

        exampleObject.ExampleValue = 123;
        exampleObject.ExampleValue = 100;
    }

    static void exampleObject_PropertyChanging(object sender, PropertyChangingEventArgs e)
    {
        if (e.PropertyName == "ExampleValue")
        {
            int originalValue = ((PropertyChangingCancelEventArgs<int>)e).OriginalValue;
            int newValue = ((PropertyChangingCancelEventArgs<int>)e).NewValue;

            // do not allow the property to be changed if the new value is less than the original value
            if(newValue < originalValue)
                ((PropertyChangingCancelEventArgs)e).Cancel = true;
        }

    }

    static void exampleObject_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "ExampleValue")
        {
            int previousValue = ((PropertyChangedEventArgs<int>)e).PreviousValue;
            int currentValue = ((PropertyChangedEventArgs<int>)e).CurrentValue;
        }
    }
}
like image 88
Dr. Wily's Apprentice Avatar answered Nov 02 '22 01:11

Dr. Wily's Apprentice


The accepted response is really bad, you can do that simply with Buffer().

Observable.FromEventPattern<PropertyChangedEventArgs>(Instance.Address, "PropertyChanged")
    .Where(e => e.EventArgs.PropertyName == "City")
    .Buffer(2,1)  //Take 2 events at a time, every 1 event
    .ObserveOn(Scheduler.ThreadPool)
    .Subscribe(search => ...); //search[0] is old value, search[1] is new value
like image 20
Nicolas Dorier Avatar answered Nov 02 '22 01:11

Nicolas Dorier