bas*_*sti 6 c# wpf user-interface mvvm
我现在正在学习WPF和MVVM(或者至少我正在尝试......).
我创建了一个小样本应用程序,它显示了一个带有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>
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
最初的UserControl(DecisionMaker)显示为假设.该方法LoadMouseView也被称为.但是View并没有改变.我错过了什么?
更新:非常感谢!我错过了INotifyPropertyChanged接口.你的所有答案都很棒,非常准确,乐于助人!我不知道接受哪一个 - 我认为接受"第一"答案是最公平的方式吗?
我接受了blindmeis的回答,因为它解决了问题并帮助我更好地理解MVVM.但是,感谢大家,每个答案都非常棒!
如果你想做mvvm - 那么你应该在viewmodel中没有引用你的view/usercontrols.你必须实现INotifyPropertyChanged!ps:如果你的Viewmodel中需要System.Windows命名空间 - 那么就出了问题.
在你的情况下你需要什么:
你的mainviewmodel应至少有2个命令来切换你的视图和1个属性的CurrentView.在您的命令中,您只需将CurrentView设置为正确的viewmodel实例.至少每个viewmodel需要两个datatemplate来定义右视图.
public object CurrentView
{
get { return _currentView; }
set {
_currentView = value; this.RaiseNotifyPropertyChanged("CurrentView");}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7754 次 |
| 最近记录: |