I think I might be doing something totally wrong here, so hopefully you guys can correct me.
I want to switch Views (switch UserControls inside a Window) using a button, then have the other View be able to have a button that switches back to the first View (like a back button). I've found how to do this using the Google, but the problem I'm running into is that I have my first View's DataContext bound to one ViewModel and the code for switching views is in another, so I can't seem to bind the button in the first View to Bind its Command to that other ViewModel. Here's what I mean (simplified):
FirstView.xaml.cs:
private readonly FirstViewModel viewModel = new FirstViewModel();
public AirplanesStatusView()
{
InitializeComponent();
DataContext = viewModel; //Bound to this viewModel for other reasons
}
FirstView.xaml:
<UserControl>
<Grid>
<Button Command="{Binding GotoSecondViewCommand}}" //This Command is in other MainWindowViewModel
</Grid>
</UserControl>
MainWindow.xaml.cs:
private readonly MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = mainWindowViewModel;
}
So then from what I found on Google, this is how it said to approach switching Views: MainWindow.xaml:
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type local:FirstViewModel}">
<local:FirstView/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:SecondViewModel}">
<local:SecondView/>
</DataTemplate>
</Window.Resources>
<ContentControl Content="{Binding CurrentView}" />
</Window>
MainWindowViewModel.cs:
private ICommand _gotoFirstViewCommand;
private ICommand _gotoSecondViewCommand;
private object _currentView;
public ICommand GotoFirstViewCommand{ //stuff }
public ICommand GotoSecondViewCommand{ //stuff }
public object CurrentView
{
get { return _currentView; }
set
{
_currentView = value;
OnPropertyChanged("CurrentView");
}
}
The problem is when I run the program, in the output it says "System.Windows.Data Error: 40 : BindingExpression path error: 'GotoSecondViewCommand' property not found on 'object' ''FirstViewModel', so the Button can't even find the command. I'm pretty sure I'm doing something totally wrong as I'm pretty new to WPF and the MVVM patter. Help and correction would be greatly appreciated.
private readonly FirstViewModel... why is this in your view and not in yourMainWindowVM? That's how you make things more complicated than they are.RelativeSourceto bind it to the parent.