Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM - How to create columns at runtime for a xamdatagrid?

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.

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.

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

How else would I achieve this?

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.

Is this approach OK without violating the MVVM pattern? Thanks

like image 480
Houman Avatar asked Aug 06 '10 16:08

Houman


1 Answers

You can use indexers:

In your ViewModel:

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

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.


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.

like image 67
Kieren Johnstone Avatar answered Nov 06 '22 20:11

Kieren Johnstone