You are right that generally you should never access views from view models. Instead in WPF, we set the DataContext
property of the view to be an instance of the relating view model. There are a number of ways to do that. The simplest but least correct is to create a new WPF project and put this into the constructor of MainWindow.xaml.cs
:
DataContext = this;
In this instance the 'view model' would actually be the code behind for the MainWindow
'view'... but then the view and view model are tied together and this is what we try to avoid by using MVVM.
A better way is to set the relationship in a DataTemplate
in the Resources
section (I prefer to use App.Resources
in App.xaml
:
<DataTemplate DataType="{x:Type ViewModels:YourViewModel}">
<Views:YourView />
</DataTemplate>
Now wherever you 'display' a view model in the UI, the relating view will automatically be shown instead.
<ContentControl Content="{Binding ViewModel}" />
A third way is to create an instance of the view model in the Resources
section like so:
<Window.Resources>
<ViewModels:YourViewModel x:Key="ViewModel" />
</Window.Resources>
You can then refer to it like so:
<ContentControl Content="{Binding Source={StaticResource ViewModel}}" />