Androme
Androme

Reputation: 2449

Xaml Dynamic Grid with Viewmodels

Hello i am trying to create a grid in xmal that is populated via a ViewModel. The grid is a 5x5 grid, and my ViewModel contains a list of "MyObject". This object contains 2 int variables Row and Column witch indicates where in the grid the Object should be. MyObject is also a view models, and the grid space should be filled with Data Template names MyTemplate with the MyObject as the DataContext. Now I pretty new to xaml and view models, but how would the best way of doing the be?

Upvotes: 0

Views: 872

Answers (1)

TDaver
TDaver

Reputation: 7264

Let's see...
Put an ObservableCollection into the VM, then...

Option 1:
...a simple Grid into V. Subscribe to it's CollectionChanged event from xaml.cs, add ContentControls for each Added object to grid, bind the ContentControl's Grid.Row and Grid.Column property to each object's properties, and set the DataContext to the object itself and ContentTemplate to Resources["MyTemplate"]. (Also, for any removed objects find the corresponding ContentControl and remove it.)
Pro: easy
Con: .cs, no designer support

Option 2:
...an ItemsControl into V. Set its ItemPanelTemplate to a Grid, and bind your ObservableCollection to its ItemsSource. Then set your Itemtemplate to MyTemplate. Now, the trick is to make the items put in the correct cell, based on your values. For that, use the ItemsControl's ItemContainerStyle property, and bind the container's Grid.Row and Column to those properties.
Pro: nice xaml and easily extended
Con: ItemContainerStyle is tricky in WPF and missing in Silverlight, so in case of the latter, you can forget it

Option 3:
...a custom panel which you write. Inherit it from Grid perhaps. Than if an element is put into it, check if it's DataContext implements an interface which contains your properties. Then use this as an ItemsPanel in Option 2...
Pro: it should work perfectly
Con: You have to write a new Panel for this...

Hopefully one of these 3 will be ok for you.

Upvotes: 1

Related Questions