WPF Datagrid使用MVVM ..是双向绑定到DataTable可能吗? [英] WPF Datagrid using MVVM.. is two way binding to DataTable possible?

查看:2792
本文介绍了WPF Datagrid使用MVVM ..是双向绑定到DataTable可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的View中有一个datagrid,它的ItemSource绑定到ViewModel中的DataTable。当我以编程方式更新DataTable(通过命令添加列)时,更改不会填充到视图。此外,如果我无效视图,通过切换到另一个选项卡,然后切换回,所做的更改显示。

I have a datagrid in my View with it's ItemSource bound to a DataTable in my ViewModel. When I update the DataTable programmatically (adding a column through a command) the changes are not populated to the View. Also, if I invalidate the View, by switching to another tab and then switching back, the changes made are shown.

我的ViewModel继承自INotifyPropertyChanged,我正在提高PropertyChanged事件正确,因为我在ViewModel中为其他绑定属性使用相同的进程,它们按预期工作。

My ViewModel inherits from INotifyPropertyChanged, and I am raising the PropertyChanged event correctly since I use the same process for other bound properties in the ViewModel and they work as expected.

是否可以获取datagrid以反映我所做的更改使用MVVM模式对绑定的DataTable做了?

Is it possible to get the datagrid to reflect changes I've made to the bound DataTable using the MVVM pattern?

有没有可以使用datagrid事件刷新视图代码中的datagrid?

Is there a datagrid event I can use to refresh the datagrid in the view's code behind?

感谢你的帮助!
-Steven

Thanks for your help! -Steven

推荐答案

在DataTable中修改行和编辑单元格内容时,反映在DataGrid中(适用于我)你是对的,ColumnChanges似乎不是。如果您使用AutoGenerateColumns选项,那么我可以想象它在初始化时会这样做,但是之后不会再看更改。

While modifying rows and editing cell contents in the DataTable get reflected in the DataGrid (works for me) you're right that ColumnChanges don't seem to be. If you're using the AutoGenerateColumns option then I imagine it does so at initialization but doesn't watch for changes afterwards.

如果您可以在列表添加到DataTable中找到发生的事件(我没有注意到一个),则可以在后面的代码中手动添加该事件。另一个可能或可能不实用的攻击将是将您的DataTable安全性设置为null,然后将属性重新设置为DataTable,每次调用OnPropertyChanged。这应该强制重建DataGrid。

If you can find an event which fires (I haven't noticed one) when a column is added to the DataTable you could then add it manually in the code behind. Another hack which may or may not be practical would be to set your DataTable propety to null, and then re-set your property to the DataTable, with OnPropertyChanged being called each time. That should force the rebuilding of the DataGrid.

private DataTable _myDataTable;

public DataTable MyDataTable
{
   get { return _myDataTable; }
   set
   {
        _myDataTable = value;
        OnPropertyChanged("MyDataTable");
   }
}

void SomeMethod()
{
     ....results in column changes
     DataTable holder;
     holder = MyDataTable
     MyDataTable = null;
     MyDataTable = holder;         
}

这篇关于WPF Datagrid使用MVVM ..是双向绑定到DataTable可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆