(WPF MVVM) How to add a user control to a View from a collection in a ViewModel
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 ItemsSource
of an ItemsControl
to 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 FooView
and BarView
user controls in your window. You will create a FooViewModel
class and a BarViewModel
class, and then create a data template for each in the resource dictionary, e.g.:
<Window.Resources>
<DataTemplate x:Key="{Type local:FooViewModel}">
<local:FooView />
</DataTemplate>
<DataTemplate x:Key="{Type local:BarViewModel}">
<local:BarView />
</DataTemplate>
</WindowResources>
Once this is done, any ItemsControl
whose ItemsSource
is bound to a collection of these view models will find the templates, create the controls, and bind them to the view models.
If the ItemsControl
you're using is a Grid
, you probably have an additional step. Any ItemsControl
generates an item container (in the case of Grid
, it's a ContentPresenter
) to hold the views it's displaying; in a Grid
, you probably need to assign the Grid.Row
and Grid.Column
to that container. Assuming that your view models have Row
and Column
properties, the way to do this is:
<Grid.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Grid.Row" Value="{Binding Row}" />
<Setter Property="Grid.Column" Value="{Binding Column}" />
</Style>
</Grid.ItemContainerStyle>
精彩评论