I'm quite new to WPF and what I'm trying to do is switch views through different command buttons.. this is my current code...
Basically I have two buttons in my MainView, SetupLan and SetupSerialPort. For simplicity, I'm currently trying to make SetupSerialPort working first. But when I click the button for it, the command executes but the view doesn't change...
App.xaml
<Application.Resources>
<DataTemplate DataType="{x:Type ViewModels:MainViewModel}">
<Views:MainView />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:SetupLanViewModel}">
<Views:SetupLanView />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:SetupSerialPortViewModel}">
<Views:SetupSerialPortView />
</DataTemplate>
</Application.Resources>
MainWindow.xaml
<Grid>
<ContentControl Content="{Binding}" />
</Grid>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
MainViewModel
public DisplaySetupSerialPortCommand SetupSerialPort
{
get; set;
}
public MainViewModel()
{
SetupSerialPort = new DisplaySetupSerialPortCommand(this);
}
MainView
<StackPanel>
<Button Height="50" Width="150" HorizontalAlignment="Left"Command="{Binding SetupLan}">Lan</Button>
<Button Height="50" Width="150" HorizontalAlignment="Left" Command="{Binding SetupSerialPort}">Serial Port</Button>
</StackPanel>
DisplaySetupSerialPortCommand
class DisplaySetupSerialPortCommand : ICommand
{
private BaseViewModel _baseViewModel;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public DisplaySetupSerialPortCommand(BaseViewModel baseViewModel)
{
_baseViewModel = baseViewModel;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_baseViewModel.ViewModel = new SetupSerialPortViewModel();
}
}