I have been stuck with this problem for a few hours now. I followed this answer which seemed to be the most relevant (no frameworks) WPF MVVM navigate views, but I am missing something and it doesn't work. It only displays the .toString method on the screen instead of the actual data template.
What I have is a MainWindow.xaml
, View1.xaml
and View2.xaml
and associated ViewModels. Both Views have buttons that can go to the other view. Why does ContentControl only displays .toString()?
MainWindow.xaml
<Window.Resources>
<DataTemplate x:Key="View1Template" DataType="{x:Type viewmodels:View1Model}">
<views:View1 />
</DataTemplate>
<DataTemplate x:Key="View2Template" DataType="{x:Type viewmodels:View2Model}">
<views:View2 />
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding CurrentView}" />
</Grid>
MainWindowViewModel.cs
public class MainWindowViewModel : ViewModelBase
{
private ViewModelBase currentView;
public ViewModelBase CurrentView
{
get
{
return currentView;
}
set
{
if (currentView != value)
{
currentView = value;
OnPropertyChanged("CurrentView");
}
}
}
public MainWindowViewModel ()
{
CurrentView = new View1Model();
}
}
How should I make this work? Moreover, where should the commands for swapping the views be? In this MainWindowViewModel.cs
?
DataContext is set in the code-behind.