我创建了一个小样本应用程序,它显示了一个带有2个按钮的窗口,每个按钮都应显示一个新的View on Click.所以我创建了3个UserControls(带有2个按钮的DecisonMaker,以及每个“clicktarget”的一个Usercontrol).
所以我将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方法.但是View并没有改变.我错过了什么?
更新:非常感谢!我错过了INotifyPropertyChanged接口.你的所有答案都很棒,非常准确,乐于助人!我不知道接受哪一个 – 我认为接受“第一”答案是最公平的方式吗?
我接受了blindmeis的回答,因为它解决了问题并帮助我更好地理解MVVM.但是,感谢大家,每个答案都非常棒!
解决方法
在你的情况下你需要什么:
> 1 mainviewmodel
> 1用于UserControlMouse的viewmodel
> 1用于UserControlTouch的viewmodel
> UserControlMouse的1个视图/用户控件
> 1用于UserControlTouch的view / usercontrol
你的mainviewmodel应至少有2个命令来切换你的视图和1个属性的CurrentView.在您的命令中,您只需将CurrentView设置为正确的viewmodel实例.至少每个viewmodel需要两个datatemplate来定义右视图.
public object CurrentView
{
get { return _currentView; }
set {
_currentView = value; this.RaiseNotifyPropertyChanged("CurrentView");}
}
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.Resources>
<DataTemplate DataType="{x:Type local:MyMouseviewmodel}">
<local:MyMouseUserControlView/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:MyTouchviewmodel}">
<local:MyTouchUserControlView/>
</DataTemplate>
</Window.Resources>
<Window.DataContext>
<local:MainWindowviewmodel />
</Window.DataContext>
<Grid>
<!-- here your buttons with command binding,i'm too lazy to write this. -->
<!-- you content control -->
<ContentControl Content="{Binding CurrentView,Mode=OneWay}" />
</Grid>
</Window>