1

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.

Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047
  • There's an answer here: http://stackoverflow.com/questions/768304/wpf-mvvm-convention-over-configuration-for-resourcedictionary – Joe White Jun 22 '09 at 16:47

1 Answers1

-1

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
  • 28,894
  • 13
  • 84
  • 111