1
votes

I have a request where I need to design a WPF screen using MVVM. This screen has two DataGrids.

The first datagrid will be bound to a collection where the datagrid will be able to add or remove items from it.

Now, the tricky part is that I need the second DataGrid to have its columns automatically generated from the items in the collection that the first datagrid is bound to.

Example:

If the first DataGrid has three lines:

| Value 1 |
| Value 2 |
| Value 3 |

I need my second datagrid to have those three columns:

| Value 1 | Value 2 | Value 3 |

However, I'm trying to think of a way to implement this which doesn't involve manually adding those columns to the second datagrid, because I believe that would kill the "MVVM way" of doing things for two reasons:

  1. I want the code-behind file for my view to remain "empty" (I cannot add any code to it other than the automatically generated "InitializeCOmponent()" on the view's constructor)

  2. I can't let my ViewModel to actually hold a reference to the DataGrid, as I believe that would create a strong tie from the View to the ViewModel.

Because of those two reasons, does anyone know a way of doing this involving only bindings (or other solutions that don't break those two rules?)

1

1 Answers

1
votes
  1. Bind a DataTable to the first DataGrid.
  2. Then transpose the DataTable (Exchange rows and columns) and bind it to the second DataGrid.

Here you have to set the AutoGeneratedColumns property of the DataGrid to true.

Please look at this article to transpose a DataTable.

Here is a simple solution to bind DataTable to a DataGrid.

If you already have bound a Collection to the first DataGrid, you can define a new DataTable and logically assigned values from the Collection and then you can bind the DataTable to the DataGrid too.