I am not totally new to MVVM or WPF but I have this problem where I want to switch from one window to another in WPF using the MVVM pattern. I can get it to work when switching between UserControls, but not Windows. I have looked at the following:
WPF MVVM Switching Between Usercontrols
It seems that it almost works, but it goes into break mode after switching window instead of displaying the window.
So what I got so far is:
- Two windows (WPF)
- A base view model implementing INotifyPropertyChanged and two view models inheriting from it.
The code below is simply from a simple project I made in order to try to make this work.
I have made the following Datatemplates in the App.xaml as suggested above:
<Application.Resources>
<DataTemplate DataType="{x:Type local:MainWindowVM}">
<local:MainWindow/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:SignUpVM}">
<local:SignUpWindow/>
</DataTemplate>
</Application.Resources>
My MainWindowVM got a command used to instantiate the new view model in order to change view:
private BaseVM _viewModel;
public BaseVM ViewModel {
get => _viewModel;
set {
_viewModel = value;
OnPropertyChanged();
}
}
public ICommand SignUpCmd { get; set; }
public MainWindowVM()
{
SignUpCmd = new SignUpCommand(this);
}
public void Execute()
{
ViewModel = new SignUpVM();
}
The corresponding xaml code for the MainWindow:
<Grid>
<ContentControl Content="{Binding ViewModel, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="Sign Up" Width="100" Height="100" Command="{Binding SignUpCmd}"/>
</Grid>
Then for the SignUpWindow the view model and view is simply empty.
So I tried debugging and I can see that it do change view and initializes the SignUpWindow by calling the InitializeComponent method in the constructor:
public SignUpWindow()
{
InitializeComponent();
}
But after that it goes into breakmode with the following error:
System.Windows.Markup.XamlParseException: Window must be the root of the tree. Cannot add Window as a child of Visual
So my initial thoughts on why this does not work is that I can not use the
local:MainWindow and local:SignUpWindow in the App.xaml,
simply because they are Windows.
I do not know if this is the proper way of switching between windows and I would really appreciate if someone can spot the error or give an alternative, thanks :)