【问题标题】:Winforms MVVM GridView DataBindingWinforms MVVM GridView 数据绑定
【发布时间】:2015-04-29 05:36:52
【问题描述】:

我正在尝试在 MVVM 模式中使用 BindingList<T> 绑定 GridView。

在我的代码中,我将gridview绑定如下:

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;

我有一个添加按钮,它以ICommand 的形式调用上下文中的方法:

Context.myCommand.Execute(null);

最后,在命令本身(在 Context 类中),我执行以下操作:

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 AFTER 中调用了以下代码:

myList = new BindingList<T>
RaisePropertyChanged("MyList");

我知道这是 WPF 的想法,这将无缝更新数据绑定。

据我了解,BindingSource 似乎不听数据源本身的变化(即指向对象的指针),而不是其内容的变化。

有人愿意确认这种行为吗? 谢谢! N.

【问题讨论】:

标签: c# winforms mvvm binding


【解决方案1】:

要解决这个问题,只需将绑定设置为数据源,如下所示:

myGrid.DataBindings.Clear(); // binding must be unique, make sure it is!    
myGrid.DataBindings.Add("DataSource", Context, "MyList");

然后,只要在“上下文”级别引发属性更改,就可以了。

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 2018-01-01
    相关资源
    最近更新 更多