简单的小型INotifyPropertyChanged实现

Vac*_*ano 4 wpf inotifypropertychanged

说我有以下课程:

public MainFormViewModel
{
    public String StatusText {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

将我对StatusText的更改反映到绑定到它的任何控件的最简单最简单的方法是什么?

显然我需要使用INotifyPropertyChanged,但有没有一种很酷的方法来做到这一点,不会弄乱我的代码?需要大量文件?等等?

注意:如果这是一个骗局,那么我很抱歉.我搜索并找不到任何东西,但使用T4代码生成听起来不容易(至少设置).

Tho*_*que 5

不幸的是,C#没有提供一种自动执行此操作的简单机制...有人建议创建一个这样的新语法:

public observable int Foo { get; set; }
Run Code Online (Sandbox Code Playgroud)

但是我怀疑它会被包含在语言中......

一个可能的解决方案是使用像Postsharp这样的AOP框架,这样你只需要用属性来装饰你的属性:

public MainFormViewModel : INotifyPropertyChanged
{
    [NotifyPropertyChanged]
    public String StatusText {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

(没试过,但我很确定Postsharp允许你做那种事......)


更新:好的,我设法让它工作.请注意,这是一个非常粗略的实现,使用私有字段上的反射来检索委托......它当然可以改进,但我会留给你;)

[Serializable]
public class NotifyPropertyChangedAttribute : LocationInterceptionAspect
{
    public override void OnSetValue(LocationInterceptionArgs args)
    {
        object oldValue = args.GetCurrentValue();
        object newValue = args.Value;
        base.OnSetValue(args);
        if (args.Instance is INotifyPropertyChanged)
        {
            if (!Equals(oldValue, newValue))
            {
                RaisePropertyChanged(args.Instance, args.LocationName);
            }
        }
    }

    private void RaisePropertyChanged(object instance, string propertyName)
    {
        PropertyChangedEventHandler handler = GetPropertyChangedHandler(instance);
        if (handler != null)
            handler(instance, new PropertyChangedEventArgs(propertyName));
    }

    private PropertyChangedEventHandler GetPropertyChangedHandler(object instance)
    {
        Type type = instance.GetType().GetEvent("PropertyChanged").DeclaringType;
        FieldInfo propertyChanged = type.GetField("PropertyChanged",
                                                  BindingFlags.Instance | BindingFlags.NonPublic);
        if (propertyChanged != null)
            return propertyChanged.GetValue(instance) as PropertyChangedEventHandler;

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您的类仍需要实现该INotifyPropertyChanged接口.您只需在属性设置器中显式提升事件即可.