One of the easiest ways to associate any data type with XAML controls is to use a DataTemplate
. Therefore, you can simply add something like this into your Application.Resources
and as long as you do not set the x:Key
properties on the DataTemplate
s, then they will be explicitly applied by the Framework whenever it comes across instances of your view models:
<DataTemplate DataType="{x:Type ViewModels:HomeViewModel}">
<Views:HomeView />
</DataTemplate>
...
<DataTemplate DataType="{x:Type ViewModels:MainViewModel}">
<Views:MainView />
</DataTemplate>
Then displaying the view is as simple as this:
<ContentControl Content="{Binding YourViewModelProperty"} />
In code behind, or your view model:
YourViewModelProperty = new MainViewModel();
It's often handy to create a base class for your view models and then the YourViewModelProperty
can of that type and you will be able to interchange them using the same property and ContentControl
.
UPDATE >>>
The general idea is that you have one MainViewModel
class with one BaseViewModel
property data bound to one ContentControl
in MainWindow.xaml
... the navigation controls should also be in MainWindow.xaml
and not in the views themselves. In this way, the MainViewModel
class is responsible for changing the property to the relevant view model instances when it receives navigation Command
s from the MainWindow.xaml
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…