c# - 如何使用 INotifyPropertyChanged 实现 DataTable 属性

标签 c# wpf mvvm datatable inotifypropertychanged

我已经创建了 WPF MVVM 应用程序,并将 WPFToolkit DataGrid 绑定(bind)设置为 DataTable,所以我想知道如何实现 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.
}

这个问题有其他解决方案吗?

最佳答案

您的表数据可以通过两种方式更改:可以从集合中添加/删除元素,或者可以更改元素中的某些属性。

第一种情况很容易处理:将您的收藏设为 ObservableCollection<T> .调用 .Add(T item).Remove(item)在您的 table 上将通过 View 为您触发更改通知(并且表格将相应更新)

第二种情况是您需要您的 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);
          }
       }
    }

现在将 View 的 datacontext 设置为 ViewModel 的实例,并绑定(bind)到集合,例如:
<tk:DataGrid 
    ItemsSource="{Binding Path=MyData}"
    ... />

希望这可以帮助 :)
伊恩

关于c# - 如何使用 INotifyPropertyChanged 实现 DataTable 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1581323/

相关文章:

c# - 使用 DataService 的性能

c# - mvvm 从加载的 View 模型中交叉执行方法

c# - 将 C# TripleDESCryptoServiceProvider 加密移植到 PHP

c# - 制作一个透明窗口作为绘图的 Canvas

c# - 通过 WPF 中的 ViewModel 将值绑定(bind)到组合框

c# - PresentationFramework.dll 中出现类型为 'System.Windows.Markup.XamlParseException' 的未处理异常

wpf - 如何在WPF中仅通过单击来获取选定的TreeViewItem?

c# - 了解Unity的GameObject.Find()、GetComponent()和对象回收

c# - 无法访问 asp.net 中的嵌入式资源

C# 验证字段的更好方法。 (Linq 到 SQL)