I want to know how to add a user control into a window from a collection. Currently I am adding my control from my Views folder to a grid cell like so.
<views:MyControl Grid.Column="0" Grid.Row="0" Margin="10"/>
I have an ObservableCollection in my view model and it stores a collection of user controls. In my view I want to take one control from that collection and place it into the cell of my grid. How can I add a control to the grid like I have done above, but from my collection?
e.g something along the lines of {Binding Path controls.[1]
If something contains a collection of user controls, it’s not a view model.
A view model that backs a view which displays other controls should contain a collection of the view models for those controls. You should be bind the
ItemsSourceof anItemsControlto the collection property, and then use template matching and data templates to create the controls.So, let’s suppose that you want to display a collection of
FooViewandBarViewuser controls in your window. You will create aFooViewModelclass and aBarViewModelclass, and then create a data template for each in the resource dictionary, e.g.:Once this is done, any
ItemsControlwhoseItemsSourceis bound to a collection of these view models will find the templates, create the controls, and bind them to the view models.If the
ItemsControlyou’re using is aGrid, you probably have an additional step. AnyItemsControlgenerates an item container (in the case ofGrid, it’s aContentPresenter) to hold the views it’s displaying; in aGrid, you probably need to assign theGrid.RowandGrid.Columnto that container. Assuming that your view models haveRowandColumnproperties, the way to do this is: