One of my favorite approaches to creating View/ViewModel pairs in WPF it to use data templates. Say you have a ViewModel called MyViewModel and it should be displayed in the UI as the View MyView.
We can create a fairly straightforward DataTemplate defined as:
<DataTemplate DataType="{x:Type local:MyViewModel}"> <local:MyView /> </DataTemplate>
Whenever we add the ViewModel instance into a Window or a ContentControl, it will render using the DataTemplate, which just happens to be the View.
If we ever run into a dynamic scenario in which we are unable to easily add static XAML as a resource dictionary into an existing resource dictionary, as we might in a Prism module scenario, we can use the following method instead. Just declare it in our MainWindow or Application and expose it through an interface inside that can be accessed through a service container.
- public void RegisterViewModelToViewMapping<tviewmodel, tview="">()
- {
- DataTemplate template = new DataTemplate(typeof(TViewModel));
- template.VisualTree = new FrameworkElementFactory(typeof(TView));
- DataTemplateKey key = new DataTemplateKey(typeof(TViewModel));
- Resources.Add(key, template);
- }