0

If I want to dynamically create a Grid with Row and Column Definitions then what would be the proper way to do so? This is probably the hardest thing for me as im not sure where to start. I know I can do this in code behind but that would be against the mvvm principles?

So my question is how can I add or bind the row / column definitions?

<Grid>
    <ColumnDefinitions>
        // Bind definitions here
    </ColumnDefinitions>

    <RowDefinitions>
        // Bind definitions here
    </RowDefinitions>
</Grid>

I cant use a uniform or datagrid grid since I have to use the normal grid due to some design decitions.

Asperger
  • 3,064
  • 8
  • 52
  • 100
  • This post might inspire you to create an attached property for your purposes: https://stackoverflow.com/questions/9000549/how-can-i-dynamically-add-a-rowdefinition-to-a-grid-in-an-itemspaneltemplate. Rachel's solution creates equally sized rows/columns – ASh Jul 03 '17 at 20:38

1 Answers1

1

I know I can do this in code behind but that would be against the mvvm principles?

No, it wouldn't. ColumnDefinitions and RowDefinitions are things that belong to the view. A view model shouldn't have any knowledge of these kind of things/elements/types.

And there is no way to bind to the Grid.ColumnDefinitions or Grid.RowDefinitions properties to some source collections.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • So what alternatives are there? – Asperger Jul 03 '17 at 14:27
  • The alternatives to doing what exactly? – mm8 Jul 03 '17 at 14:27
  • creating dynamic and responsive grids with splitters – Asperger Jul 03 '17 at 14:27
  • Writing code in the view that creates the rows and columns based on the number of items in the view model or creating a custom control that does the same. Bottom line is that you should not create your UI in the view model. – mm8 Jul 03 '17 at 14:29
  • Design view? You could add them in the constructor of the view for example. Or maybe in a Loaded event handler that will fire after any data binding has being resolved. – mm8 Jul 03 '17 at 14:30
  • So basically a seperate class that handles this sort of stuff. Its more like some sort of controller then or not sure what it is – Asperger Jul 03 '17 at 14:30
  • One question if an xaml such a usercontrol is linked to a cs file is this cs treated a viewmodel or a view? – Asperger Jul 03 '17 at 14:40
  • 1
    The *.xaml.cs is the code-behind of the view, i.e. it is a part of the same class that you define in your XAML markup. – mm8 Jul 03 '17 at 14:40
  • Oh no, I treated it as my viewmodel! ok that means I have to treat it as my view and add my viewmodel as the DataContext of my view. The view then handles the grid definitions logic. – Asperger Jul 03 '17 at 14:41
  • 1
    Thanks for your answer. Sorry again if all of this sounds weird. Im still new to the concept of mvvm. Doing a 4 year apprenticeship in application development. – Asperger Jul 03 '17 at 14:44