为什么没有人使用 INotifyPropertyChanging? [英] Why doesn't anyone use the INotifyPropertyChanging?

查看:18
本文介绍了为什么没有人使用 INotifyPropertyChanging?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 MVVM 大量使用 INotifyPropertyChanged,但我从未见过 INotifyPropertyChanging 的任何用法.有什么理由吗?

I know MVVM heavily uses the INotifyPropertyChanged, but I have never seen any usage of the INotifyPropertyChanging. Any reason why?

如果我确实想使用它,将它集成到我的 MVVM 框架中的好方法是什么?我知道你不应该在你的 ViewModel 上使用 MessageBox 因为那样你就不能对它进行单元测试.那么如何发出警报,然后继续使用 PropertyChange(如果适用)?

If I did want to use this, what would be a good way to integrate this into my MVVM Framework? I know you're not supposed to use MessageBox on your ViewModel because then you can't unit test it. So how would one go about throwing up an alert, then continuing on with the PropertyChange if applicable?

推荐答案

关于 INotifyPropertyChanging 需要记住的一点是你不能阻止变化的发生.这仅允许您记录发生的更改.

Something to keep in mind about INotifyPropertyChanging is you can't stop the change from happening. This merely allows you to record that the change occurred.

我在我的框架中使用它来跟踪更改,但它不是停止更改的合适方法.

I use it in a framework of mine for change tracking, but it isn't an appropriate method for halting changes.

您可以使用自定义接口/事件对扩展您的 ViewModelBase:

You could extend your ViewModelBase with a custom interface/event pair:

delegate void AcceptPendingChangeHandler(
    object sender,
    AcceptPendingChangeEventArgs e);

interface IAcceptPendingChange
{
    AcceptPendingChangeHandler PendingChange;
}

class AcceptPendingChangeEventArgs : EventArgs
{
    public string PropertyName { get; private set; }
    public object NewValue { get; private set; }
    public bool CancelPendingChange { get; set; }
    // flesh this puppy out
}

class ViewModelBase : IAcceptPendingChange, ...
{
    protected virtual bool RaiseAcceptPendingChange(
        string propertyName,
        object newValue)
    {
        var e = new AcceptPendingChangeEventArgs(propertyName, newValue)
        var handler = this.PendingChange;
        if (null != handler)
        {
            handler(this, e);
        }

        return !e.CancelPendingChange;
    }
}

此时您需要按照约定将其添加到您的视图模型中:

At this point you'd need to add it by convention to your view models:

class SomeViewModel : ViewModelBase
{
     public string Foo
     {
         get { return this.foo; }
         set
         {
             if (this.RaiseAcceptPendingChange("Foo", value))
             {
                 this.RaiseNotifyPropertyChanging("Foo");
                 this.foo = value;
                 this.RaiseNotifyPropretyChanged("Foo");
             }
         }
     }
}

这篇关于为什么没有人使用 INotifyPropertyChanging?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆