tags:

views:

129

answers:

2

I have a WPF application which has a MainView.xaml Window which loads numerous page objects at runtime, loads them into ViewModels, and displays them dynamically in the menu.

My MainViewModel has an ObservableCollection of ViewModels and I bind these each to their appropriate Views in the MainView.xaml file.

However, is there a way to automate this so I don't have to make these manual entries each time I add a page?

<Window.Resources>

    <DataTemplate DataType="{x:Type vm:PageItemManageCustomersViewModel}">
        <v:PageItemManageCustomersView/>
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:PageItemManageEmployeesViewModel}">
        <v:PageItemManageEmployeesView/>
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:PageItemReportsViewModel}">
        <v:PageItemReportsView/>
    </DataTemplate>

</Window.Resources>

Isn't this something that a "ServiceLocator" or "Container" should be doing, hooking up the Views to the ViewModels? I've read that the above is a common way to match up the ViewModels and Views in the MVVM pattern, but it comes across as a bit static to me. Would appreciate any thoughts.

A: 

Another option is to use a class for resolving ViewModels based on some key. You can then use this in your main view to resolve the correct viewmodel for your controls.

public static class ViewModelFactory
{
 public ViewModelBase Create(string someKeyHere)
 {
    //Some logic to resolve a view model
 }
}
Ray Booysen