如何实现与INotifyPropertyChanged的DataTable属性(How to imp

2019-08-19 12:38发布

我创建MVVM WPF应用程序,并设置WPFToolkit的DataGrid绑定到数据表中,所以我想知道如何实现DataTable属性来通知改变。 目前,我的代码如下图所示。

public DataTable Test
{
    get { return this.testTable; }
    set 
    { 
        ...
        ...
        base.OnPropertyChanged("Test");
    }
}

public void X()
{
    this.Test.Add(...); // I suppose this line will call to getter first (this.Test = get Test) and then it will call add letter, this mean that setter scope will never fire.
    base.OnPropertyChanged("Test"); // my solution is here :) but I hope it has better ways.
}

是否有针对此问题的另一个解决方案?

Answer 1:

有2种方法您表的数据可能会改变:无论是一个元素,可以添加/从集合,或从内部元件可能会改变一些属性去除。

第一种情形是容易处理:使你收集的ObservableCollection<T> 调用.Add(T item).Remove(item)在你的桌子会赴汤蹈火的改变通知查看你(和表将随之更新)

第二种情况是,你需要你的T对象执行INotifyPropertyChanged ...

最终,你的代码应该是这个样子:

    public class MyViewModel
    {
       public ObservableCollection<MyObject> MyData { get; set; }
    }

    public class MyObject : INotifyPropertyChanged
    {
       public MyObject()
       {
       }

       private string _status;
       public string Status
       {
         get { return _status; }
         set
         {
           if (_status != value)
           {
             _status = value;
             RaisePropertyChanged("Status"); // Pass the name of the changed Property here
           }
         }
       }

       public event PropertyChangedEventHandler PropertyChanged;

       private void RaisePropertyChanged(string propertyName)
       {
          PropertyChangedEventHandler handler = this.PropertyChanged;
          if (handler != null)
          {
              var e = new PropertyChangedEventArgs(propertyName);
              handler(this, e);
          }
       }
    }

现在设置你的视图的DataContext的是你的视图模型的实例,并绑定到集合,如:

<tk:DataGrid 
    ItemsSource="{Binding Path=MyData}"
    ... />

希望这有助于:)伊恩



文章来源: How to implement DataTable property with INotifyPropertyChanged