我现在正在学习
WPF和MVVM(或者至少我正在尝试……).
我创建了一个小样本应用程序,它显示了一个带有2个按钮的窗口,每个按钮都应显示一个新的View on Click.所以我创建了3个UserControls(带有2个按钮的DecisonMaker,以及每个“clicktarget”的一个Usercontrol).
所以我将MainWindow的CotentControl绑定到我的MainWindow@R_403_93@l中名为“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:MainWindow@R_403_93@l /> </Window.DataContext> <Grid> <ContentControl Content="{Binding CurrentView,Mode=OneWay}" /> </Grid> </Window>
class MainWindow@R_403_93@l { 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.但是,感谢大家,每个答案都非常棒!
解决方法
如果你想做mvvm – 那么你应该在@R_403_93@l中没有引用你的view / usercontrols.你必须实现INotifyPropertyChanged! ps:如果你的@R_403_93@l中需要System.Windows命名空间 – 那么就出了问题.
在你的情况下你需要什么:
> 1 main@R_403_93@l
> 1用于UserControlMouse的@R_403_93@l
> 1用于UserControlTouch的@R_403_93@l
> UserControlMouse的1个视图/用户控件
> 1用于UserControlTouch的view / usercontrol
你的main@R_403_93@l应至少有2个命令来切换你的视图和1个属性的CurrentView.在您的命令中,您只需将CurrentView设置为正确的@R_403_93@l实例.至少每个@R_403_93@l需要两个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:MyMouse@R_403_93@l}"> <local:MyMouseUserControlView/> </DataTemplate> <DataTemplate DataType="{x:Type local:MyTouch@R_403_93@l}"> <local:MyTouchUserControlView/> </DataTemplate> </Window.Resources> <Window.DataContext> <local:MainWindow@R_403_93@l /> </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>