BindableBase与INotifyChanged [英] BindableBase vs INotifyChanged

查看:207
本文介绍了BindableBase与INotifyChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道BindableBase是否仍然可行,还是应该坚持使用INotifyChanged事件?看来BindableBase很快失去了光泽。感谢您可以提供的任何信息。

Does anyone know if BindableBase is still a viable or should we stick with INotifyChanged events? It seems like BindableBase has lost its luster quickly. Thanks for any info you can provide.

推荐答案

INotifyPropertyChanged

ViewModel应该实现INotifyPropertyChanged接口,并在属性更改时将其引发

The ViewModel should implement the INotifyPropertyChanged interface and should raise it whenever the propertychanges

public class MyViewModel : INotifyPropertyChanged
{
    private string _firstName;


    public event PropertyChangedEventHandler PropertyChanged;

    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (_firstName == value)
                return;

            _firstName = value;
            PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
        }
    }


    }
}

问题出在 ICommand 界面上,因为大多数代码也重复了,因为它传递的字符串很容易出错。

Problem is with ICommand interface as most of the code is duplicated also since it passes string it becomes error prone.

Bindablebase 是一个抽象类,它实现INotifyPropertyChanged接口并提供 SetProperty< T> 。您可以将set方法减少为仅一行,也可以参考参数允许您更新其值。下面的BindableBase代码来自 INotifyPropertyChanged,The。 NET 4.5的方式-重新访问

Whereas Bindablebase is an abstract class that implements INotifyPropertyChanged interface and provide SetProperty<T>.You can reduce the set method to just one line also ref parameter allows you to update its value. The BindableBase code below comes from INotifyPropertyChanged, The .NET 4.5 Way - Revisited

   public class MyViewModel : BindableBase
{
    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get { return _firstName; }
        set { SetProperty(ref _firstName, value); }
    }


}

     //Inside Bindable Base
    public abstract class BindableBase : INotifyPropertyChanged
    {

       public event PropertyChangedEventHandler PropertyChanged;

       protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
       {
          if (Equals(storage, value))
          {
             return false;
          }

          storage = value;
          this.OnPropertyChanged(propertyName);
          return true;
       }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      PropertyChangedEventHandler eventHandler = this.PropertyChanged;
      if (eventHandler != null)
      {
          eventHandler(this, new PropertyChangedEventArgs(propertyName));
      }
    }
}

这篇关于BindableBase与INotifyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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