[英]How to implement DataTable property with INotifyPropertyChanged
I have created WPF MVVM application, and set WPFToolkit DataGrid binding to DataTable so I want to know how to implement DataTable property to notify changed. 我已经创建了WPF MVVM应用程序,并将WPFToolkit DataGrid绑定设置为DataTable,所以我想知道如何实现DataTable属性以通知更改。 Currently my code is like below.
目前,我的代码如下。
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.
}
Is it has another solution for this problem? 它有解决此问题的另一种方法吗?
There are 2 ways your Table data could change: Either an element could be added/removed from the collection, or some properties from within an element could change. Table数据有两种更改方式:要么可以从集合中添加/删除元素,要么可以更改元素中的某些属性。
The first scenario is easy to handle: make your collection an ObservableCollection<T>
. 第一种情况很容易处理:将您的集合设为
ObservableCollection<T>
。 Invoking .Add(T item)
or .Remove(item)
on your table will fire a change notification through to the View for you (and the table will update accordingly) 在表上调用
.Add(T item)
或.Remove(item)
将为您触发更改通知到视图(并且表将相应更新)
The second scenario is where you need your T object to implement INotifyPropertyChanged... 第二种情况是您需要T对象来实现INotifyPropertyChanged ...
Ultimately your code should look something like this: 最终,您的代码应如下所示:
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);
}
}
}
Now set the datacontext of your View to be an instance of your ViewModel, and bind to the collection, like: 现在将View的datacontext设置为ViewModel的实例,并绑定到该集合,例如:
<tk:DataGrid
ItemsSource="{Binding Path=MyData}"
... />
Hope this helps :) Ian 希望这会有所帮助:)伊恩
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.