Bind multiple views to multiple viewmodels

c#, mvvm, user-interface, wpf

Solution

Typically I use implicit `DataTemplates` for mapping `Views` to `ViewModels`. They can go in `<Application.Resources>`, `<Window.Resources>` or even in under specific elements only such as `<TabControl.Resources>`

<DataTemplate DataType="{x:Type local:PanelViewModel}">
    <myControls:vwPanel />
</DataTemplate>

This means that anytime WPF encounters an object in the VisualTree of type `PanelViewModel`, it will draw it using `vwPanel`

Objects typically get placed in the `VisualTree` through an `ItemsSource` property

<ItemsControl ItemsSource="{Binding CollectionOfAllPanels}" />

or by using a `ContentControl`

<ContentControl Content="{Binding PanelVM1}" />

Problem

I have a WPF window displaying different self-defined Views. So far I was able to use everything I learned about MVVM :) Now I got to a new "problem": I have 10 entities of the same view in a bigger view. These ten view-entities contain a set of controls (textbox, combobox etc.) but are all consistent. So how do I bind these Views to a ViewModel? I thought about having 10 instances of the ViewModel in the "higher-level" ViewModel and give the views fix-defined the instances of the VM as datacontext. My question is now --> Is there a easier (or more convienient) way to bind many (identical) views to their viewmodels? Code-Example: View Model: ``` private PanelViewModel _panelViewModel1 = new PanelViewModel(); public PanelViewModel PanelVM1 { get { return _panelViewModel1; } } ``` View-Example: ``` <myControls:vwPanel HorizontalAlignment="Left" x:Name="vwPanel1" VerticalAlignment="Top" DataContext="{Binding Path=PanelVM1}"/> ``` What bothers me is that I would need this logic ten times for ten views? UPDATE: To answer some questions: I want to show one view 10 times (in my example) I defined my own view by inheriting from UserControl. So my `vwPanel` inherits from `UserControl`. The 10 vwPanels are just placed inside a StackPanel inside a Grid. It's not about displaying data, as you pointed out, there would be a listview or a datagrid a better place to start. It's a special case where I need this much input-controls :/ UPDATE2: What I hoped for was more like defining a List of ViewModels and Bind my 10 Views to one of this List. But this will not work will it? At least I wouldn't know how to refernce one "special" entitiy in the list out of XAML...

Original source