NotifyPropertyChanged事件,其中事件args包含旧值

时间:2011-10-06 17:00:40

标签: c# wpf events .net-3.5

是否存在类似于INotifyPropertyChanged的接口,其中事件args包含要更改的属性的旧值,或者我是否必须扩展该接口以创建一个?

例如:

    public String ProcessDescription
    {
        get { return _ProcessDescription; }
        set
        {
            if( value != ProcessDescription )
            {
                String oldValue = _ProcessDescription;
                _ProcessDescription = value;
                InvokePropertyChanged("ProcessDescription", oldvalue);
            }
        }
    }

    InvokePropertyChanged(String PropertyName, OldValue)
    {
         this.PropertyChanged( new ExtendedPropertyChangedEventArgs(PropertyName, OldValue) );
    }

我也会讨论提供此信息的类似PropertyChanging的事件,无论它是否支持e.Cancel。

5 个答案:

答案 0 :(得分:36)

如答案所示,我必须实施自己的解决方案。为了别人的利益,我在这里提出了这个问题:

扩展PropertyChanged事件

此活动专门设计为向后兼容旧的propertyChanged事件。它可以与调用者使用简单的PropertyChangedEventArgs互换使用。当然,在这种情况下,事件处理程序有责任检查传递的PropertyChangedEventArgs是否可以向下转换为PropertyChangedExtendedEventArgs,如果他们想要使用它。如果他们感兴趣的只是PropertyName属性,则不需要向下转换。

public class PropertyChangedExtendedEventArgs<T> : PropertyChangedEventArgs
{
    public virtual T OldValue { get; private set; }
    public virtual T NewValue { get; private set; }

    public PropertyChangedExtendedEventArgs(string propertyName, T oldValue, T newValue)
        : base(propertyName)
    {
        OldValue = oldValue;
        NewValue = newValue;
    }
}

扩展PropertyChanged接口

如果程序员想创建一个强制通知属性包含旧值和新值的事件,他们只需要实现以下界面:

// Summary: Notifies clients that a property value is changing, but includes extended event infomation
/* The following NotifyPropertyChanged Interface is employed when you wish to enforce the inclusion of old and
 * new values. (Users must provide PropertyChangedExtendedEventArgs, PropertyChangedEventArgs are disallowed.) */
public interface INotifyPropertyChangedExtended<T>
{
    event PropertyChangedExtendedEventHandler<T> PropertyChanged;
}

public delegate void PropertyChangedExtendedEventHandler<T>(object sender, PropertyChangedExtendedEventArgs<T> e);

示例1

用户现在可以指定更高级的NotifyPropertyChanged方法,允许属性设置者传递旧值:

public String testString
{
    get { return testString; }
    set
    {
        String temp = testString;
        testValue2 = value;
        NotifyPropertyChanged("TestString", temp, value);
    }
}

您的新NotifyPropertyChanged方法如下所示:

protected void NotifyPropertyChanged<T>(string propertyName, T oldvalue, T newvalue)
{
    OnPropertyChanged(this, new PropertyChangedExtendedEventArgs<T>(propertyName, oldvalue, newvalue));
}

OnPropertyChanged和以前一样:

public virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
        handler(sender, e);
}

示例2

或者,如果您更喜欢使用lambda表达式并完全取消硬编码的属性名称字符串,则可以使用以下内容:

public String TestString
{
    get { return testString; }
    private set { SetNotifyingProperty(() => TestString, ref testString, value); }
}

以下魔术支持:

protected void SetNotifyingProperty<T>(Expression<Func<T>> expression, ref T field, T value)
{
    if (field == null || !field.Equals(value))
    {
        T oldValue = field;
        field = value;
        OnPropertyChanged(this, new PropertyChangedExtendedEventArgs<T>(GetPropertyName(expression), oldValue, value));
    }
}
protected string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression memberExpression = (MemberExpression)expression.Body;
    return memberExpression.Member.Name;
}

<强>性能

如果需要考虑表现,请参阅此问题:Implementing NotifyPropertyChanged without magic strings

总之,开销很小。添加旧值并切换到扩展事件大约减少15%,仍然允许每秒一百万个属性通知的顺序,并且切换到lambda表达式是5倍减速,允许每个大约十万个属性通知第二。这些数字远远不能在任何UI驱动的应用程序中形成瓶颈。

答案 1 :(得分:3)

听起来您想将INotifyPropertyChangingINotifyPropertyChanged结合使用。 Msdn文档http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanging.aspx

答案 2 :(得分:1)

如果您只想要旧值,则可以在更改属性值之前调用该事件。但这将是这个事件通常如何使用的背离,所以我会为它创建一个专用的接口和args。

答案 3 :(得分:1)

不,你必须从零开始创建自己的。

我曾经在我的研究项目Granite中做同样的事情,但我开始意识到这不值得付出代价。我计算的属性太多了,并且为了举起一个事件而必须运行它们两次太昂贵了。

答案 4 :(得分:1)

accepted answer很不错,但是我努力遵循应该如何实现PropertyChangedExtendedEventArgs<T>的方法,但最终我意识到实际上并非如此。

下面是一个完整的工作示例,展示了如何使用PropertyChangedExtendedEventArgs<T>

using System;
using System.ComponentModel;

namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Run();
        }

        private void Run()
        {
            // Create Poco
            var poco = new MyPoco(1, "MyOldName", 150);
            // Attach property changed event
            poco.PropertyChanged += PocoOnPropertyChanged;
            // Change data
            poco.Id = 10;
            poco.Name = "NewName";
            poco.Height = 170;
        }

        /// <summary>
        /// Property changed handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PocoOnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // Without casting 'e' is a standard PropertyChanged event
            if (Equals(e.PropertyName, nameof(MyPoco.Id)))
            {
                Console.WriteLine($"'{nameof(MyPoco.Id)}' has changed, but we have no other data");
            }

            // New extended property changed event of type 'string'
            if (Equals(e.PropertyName, nameof(MyPoco.Name)))
            {
                // Need to cast into type we know and are expecting
                if (e is PropertyChangedExtendedEventArgs<string> extended)
                {
                    Console.WriteLine(
                        $"'{nameof(MyPoco.Name)}' has changed, from '{extended.OldValue}' to '{extended.NewValue}'.");
                }
            }

            // New extended property changed event of type 'double'
            if (Equals(e.PropertyName, nameof(MyPoco.Height)))
            {
                // This cast will fail as the types are wrong
                if (e is PropertyChangedExtendedEventArgs<string>)
                {
                    // Should never hit here
                }
                // Cast into type we know and are expecting
                if (e is PropertyChangedExtendedEventArgs<double> extended)
                {
                    Console.WriteLine(
                        $"'{nameof(MyPoco.Height)}' has changed, from '{extended.OldValue}' to '{extended.NewValue}'.");
                }
            }
        }
    }

    /// <summary>
    /// Example POCO
    /// </summary>
    public sealed class MyPoco : NotifyBase
    {
        private int _id;
        private string _name;
        private double _height;

        public MyPoco(int id, string name, double height)
        {
            _id = id;
            _name = name;
            _height = height;
        }

        public int Id
        {
            get => _id;
            set
            {
                var old = _id;
                _id = value;
                OnPropertyChanged(old, value, nameof(Id));
            }
        }

        public string Name
        {
            get => _name;
            set
            {
                var old = _name;
                _name = value;
                OnPropertyChanged(old, value, nameof(Name));
            }
        }

        public double Height
        {
            get => _height;
            set
            {
                var old = _height;
                _height = value;
                OnPropertyChanged(old, value, nameof(Height));
            }
        }
    }

    /// <summary>
    /// Notifying base class
    /// </summary>
    public abstract class NotifyBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged<T>(T oldValue, T newValue, string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedExtendedEventArgs<T>(oldValue, newValue, propertyName));
        }
    }

    /// <summary>
    /// Extended property changed
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class PropertyChangedExtendedEventArgs<T> : PropertyChangedEventArgs
    {
        public PropertyChangedExtendedEventArgs(T oldValue, T newValue, string propertyName)
            : base(propertyName)
        {
            OldValue = oldValue;
            NewValue = newValue;
        }

        public T OldValue { get; }
        public T NewValue { get; }
    }
}

输出:

'Id' has changed, but we have no other data
'Name' has changed, from 'MyOldName' to 'NewName'.
'Height' has changed, from '150' to '170'.