我已经创建了 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/