如何公开 DataGrids Columns 属性以与 Viewmodel 中的属性绑定?
在我的视图模型中,根据给定的数据类型,我生成列(使用反射获取数据类型的所有属性并使用它们创建适当的数据网格列)并将其添加到列集合中。现在我想将此 Collection 绑定到我的数据网格的 columns 属性,如下所示:
请让我知道如何在不破坏 MVVM 的情况下实现这一目标?
In my Viewmodel, depending upon given datatype I am generating column( using reflection get all properties of datatype and use them to create appropriate datagrid column) and adding it to Columns collection. Now I want to bind this Collection to my datagrid's columns property, like below:
<DataGrid Columns="{Binding VMColumnCollection}" />
Please let me know how to achieve this without breaking MVVM ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能这样做,但有一个解决方法,请检查此解决方案: Stackoverflow 中的答案
You cannot do that, but there is a workaround, check this solution: Answer in Stackoverflow
我得到了解决方案,问题不在于附加属性。实际上,我在 TabControl 中使用了 datagrid。但是当我从第一个选项卡切换到第二个选项卡,然后再次切换回第一个选项卡时,从附加属性生成了一个异常,即“列 xyz 已经存在......”,但 Datagrid. Columns.Count 为 0。这很奇怪,即使列数为 0,我也无法插入列(尽管我无法找到发生这种情况的原因)。然后在调试时发现,每当我切换回以前的状态时选项卡,视图的构造函数是调用。切换回选项卡不应创建新的视图实例,我在互联网上搜索并找到以下链接
如何保留 TabControl 中选项卡项内的控件状态
http://eric.burke.name/dotnetmania/2009/04/26/ 22.09.28
然后我创建了一个自定义 Tabcontrol,如第二个链接所示。现在它正在发挥作用。
I got the solution, the problem was not with the attached property. Actually I was using datagrid inside TabControl.But when I was switching from first tab to second tab and then again back to first, an exception was getting generated from attached property that 'column xyz already exist.....' but the Datagrid.Columns.Count was 0. This was very strange even though columns count is 0, i can't insert a column ( although I am not able to find why this happened).Then while debugging found that whenever i was switching back to my previous tab, constructor of view was called.Switching back to tab should not create new instance of View, I searched on internet and found below links
How to preserve control state within tab items in a TabControl
http://eric.burke.name/dotnetmania/2009/04/26/22.09.28
then I created a custom Tabcontrol as shown in 2nd link. Now it is working.