我现在正在学习WPF和MVVM(或者至少我在尝试...)。
我创建了一个小的示例应用程序,显示一个带有2个按钮的窗口,每个按钮应该在单击时显示一个新视图。因此我创建了3个用户控件(带有2个按钮的DecisonMaker,以及每个“clicktarget”的一个用户控件)。
因此,我将MainWindow的CotentControl绑定到MainWindowViewModel中名为“CurrentView”的属性。
MainWindow.xaml代码如下:
我创建了一个小的示例应用程序,显示一个带有2个按钮的窗口,每个按钮应该在单击时显示一个新视图。因此我创建了3个用户控件(带有2个按钮的DecisonMaker,以及每个“clicktarget”的一个用户控件)。
因此,我将MainWindow的CotentControl绑定到MainWindowViewModel中名为“CurrentView”的属性。
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 的代码:
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();
}
}
最初的UserControl(DecisionMaker)显示正常。也调用了LoadMouseView
方法。但是视图没有改变。我错过了什么?
更新:非常感谢!我错过了INotifyPropertyChanged接口。你们所有人的回答都非常好,准确和有帮助!我不知道该接受哪一个 - 我认为接受“第一个”答案是最公平的方式吗?
我接受了blindmeis的答案,因为它解决了问题并帮助我更好地理解了MVVM。但每个答案都非常棒,感谢你们所有人!