我已经创建了 WPF MVVM 应用程序,并将 WPFToolkit DataGrid 绑定设置为 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> http://msdn.microsoft.com/en-us/library/ms668604.aspx。调用.Add(T item)
or .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);
}
}
}
现在将视图的数据上下文设置为 ViewModel 的实例,并绑定到集合,例如:
<tk:DataGrid
ItemsSource="{Binding Path=MyData}"
... />
希望这可以帮助 :)
伊恩
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)