我试图使用MVVM模式中的GridView来绑定BindingList<T>。
在我的代码中,我将网格视图绑定如下:
BindingSource bindingSource = new BindingSource(Context.MyList, null);
bindingSource.CurrentChanged += Context.BindingSourceCurrentItemChanged;
// NOTE: this part is to test if the event is fired...
Context.MyList.ListChanged += myList_ListChanged;
myGrid.DataSource = bindingSource;我有一个add按钮,它以ICommand的形式调用上下文中的方法
Context.myCommand.Execute(null);最后,在命令本身(在上下文类中)中,我执行以下操作:
MyList.Add(new Item());非常直接的实现..。bindingSource.CurrentChanged确实可以正常运行,但我从不输入myList_ListChanged事件。
如果我停止启动ICommand并添加几个项,那么Context.MyList计数确实会被更新。如果我使用删除命令,也会发生同样的情况..。
我有什么明显的遗漏吗?
谢谢你,N.
编辑我意识到,对于这个问题,是因为我将MyList作为属性,如下所示:
BindingList<T> myList;
public BindingList<T> MyList {
get {
if (myList == null) { myList = new BindingList<T>();}
return myList;
}
}我在表单的构造函数中创建BindingSource,而在ViewModel 中调用的代码是之后绑定的:
myList = new BindingList<T>
RaisePropertyChanged("MyList");我知道这是WPF的想法,这样就可以无缝地更新数据绑定。
据我所知,BindingSource似乎不听取数据源本身的变化(即指向对象的指针),而不是其内容的更改。
有人愿意证实这种行为吗?谢谢!N.
发布于 2015-03-03 12:59:28
要克服这个问题,只需将绑定设置为:
myGrid.DataBindings.Clear(); // binding must be unique, make sure it is!
myGrid.DataBindings.Add("DataSource", Context, "MyList");然后,只要在“上下文”级别引发属性更改,就可以了。
https://stackoverflow.com/questions/28749295
复制相似问题