MVVM-如何在运行时为xamdatagrid创建列? [英] MVVM - How to create columns at runtime for a xamdatagrid?

查看:75
本文介绍了MVVM-如何在运行时为xamdatagrid创建列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个XamDataGrid,以显示从x到y的时间范围内的动态列数.因此,我不知道用户会选择多少年才能预先创建这些列.

I have to create a XamDataGrid that shows a dynamic amount of columns for a time frame x to y. Therefore I dont know how many years a user would select to have these columns created upfront.

现在,通常在MVVM中,您只需通过XamDataGrid中需要的列填充所有属性中的数据,后者就会自动生成它们.

Now usualy within MVVM you would just populate the data through as many Properties as you would need Columns within your XamDataGrid, and the latter would just autogenerate them.

很明显,除非我对反射做一些疯狂的工作,否则我无法在运行时在ViewModel中创建属性.

Obviously I couldn't just create Properties within my ViewModel at runtime unless I did something crazy with Reflection.

我还能怎么实现呢?

我应该为数据网格创建未绑定字段并通过代码填充它们吗?我同意在这个阶段我不需要双向绑定,因为网格只是只读的……只是想大声一点.

Should I just create unbound fields for the datagrid and fill them through code? I agree I wont need a two way Binding at this stage, since the grid is only readonly...just thinking loud.

在不违反MVVM模式的情况下,这种方法可以吗? 谢谢

Is this approach OK without violating the MVVM pattern? Thanks

推荐答案

您可以使用索引器:

在您的ViewModel中:

In your ViewModel:

public MyVariableCollection RowData
{
    get { return new MyVariableCollection(this); }
}

MyVariableCollection中: 受保护的SomeRowViewModel viewModel;

In MyVariableCollection: protected SomeRowViewModel viewModel;

public MyVariableCollection(SomeRowViewModel viewmodel)
{
    this.viewModel = viewmodel;
}

public object this[string name]
{
    get { return viewModel.GetRowColumnValue(name); }
}

我试图保持简短:但是想法是,您有一个定义了索引器的新类,然后可以像这样进行绑定:

I've tried to keep it brief: but the idea is, you have a new class with an indexer defined, then you can bind like this:

{Binding Path=SomeRowViewModelInstance.RowData["ColumnName"]}

数据网格控件上的列集合将被绑定-您可以为每个列设置一个列模板以绑定到有问题的列;您不需要像这样在索引器中使用文字字符串.

The column collection on the data grid control would be bound - and you could set a column template for each column to bind to the column in question; you needn't use a literal string in the indexer like that.

希望为您提供一些思考的机会-有关此路线的任何问题,请发表评论.

Hope that provides some food for thought - any questions on this route please leave a comment.

编辑时要另外考虑:我已经使用内容ComponentModel命名空间来生成自定义的TypeDescriptor.它相当深入,但是您可以使一个对象出现"以具有其他或自定义属性.它比我上面发布的indexer方法要复杂得多,但是如果您遇到问题,值得一看.

Edit for an additional thought: I have used the contents ComponentModel namespace to produce a custom TypeDescriptor. It is fairly in depth but you can make an object 'appear' to have additional or custom properties. It's far more complex than the indexer method I posted above but if you get stuck it's worth a look.

这篇关于MVVM-如何在运行时为xamdatagrid创建列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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