I am studying WPF and MVVM at the moment (or at least I'm trying ...).
I created a small sample application that shows a window with two buttons, each of which should show a new view on click. So I created 3 UserControls (DecisonMaker with 2 buttons and one Usercontrol for each "clicktarget").
So, I bound the CotentControl MainWindow to a property called CurrentView in my MainWindowViewModel
Code MainWindow.xaml:
<Window x:Class="WpfTestApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfTestApplication" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <local:MainWindowViewModel /> </Window.DataContext> <Grid> <ContentControl Content="{Binding CurrentView, Mode=OneWay}" /> </Grid> </Window>
MainWindowViewModel Code:
class MainWindowViewModel { private UserControl _currentView = new DecisionMaker(); public UserControl CurrentView { get { return _currentView; } set { _currentView = value; } } public ICommand MausCommand { get { return new RelayCommand(LoadMouseView); } } public ICommand TouchCommand { get { return new RelayCommand(LoadTouchView); } } private void LoadMouseView() { CurrentView = new UserControlMouse(); } private void LoadTouchView() { CurrentView = new UserControlTouch(); } }
The initial UserControl (DecisionMaker) is displayed as expected. The LoadMouseView
method is also called. But the view does not change. What am I missing?
UPDATE: Thanks so much! I skipped the INotifyPropertyChanged interface. All your answers were just wonderful and very accurate and helpful! I donβt know which one to accept - I think this is the fairest way to accept the "first" answer?
I accepted blindmeis answer as it solved the problem and helped me better understand MVVM. But every answer was really great thanks to all of you!
source share