【发布时间】:2020-06-11 20:28:04
【问题描述】:
我正在尝试学习 WPF/MVVM,目前正在研究如何在视图之间切换。我首先在互联网上寻找一些例子来学习。我使用的非常简单:两个视图(名为“Home”和“Account”)只显示一个标签,以保持 xaml 和 VM 的简单性,以及一个带有两个按钮的主窗口,用于在视图之间切换。
DataTemplates 在 App.xaml 文件中声明(与命名空间一起),因此它们对整个项目应该是全局的:
<Application.Resources>
<DataTemplate DataType="{x:Type viewmodels:HomeViewModel}">
<views:HomeView/>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:AccountViewModel}">
<views:AccountView/>
</DataTemplate>
</Application.Resources>
按照我的理解,这个技巧是由第三个 VM(称为 MainViewModel.cs)完成的,它实现了一个 SelectedViewModel 属性,该属性跟踪必须显示的 VM,以及绑定到按钮的 ICommand:
private BaseViewModel _selectedViewModel;
public BaseViewModel SelectedViewModel
{
get { return _selectedViewModel; }
set
{
_selectedViewModel = value;
OnPropertyChanged(nameof(SelectedViewModel));
}
}
public ICommand UpdateViewCommand { get; set; }
MainWindow.xaml 如下所示:
<ContentControl Grid.Row="0" Content="{Binding SelectedViewModel}"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center">
<Button Margin="10" Width="200" Content="Home" Command="{Binding UpdateViewCommand}" CommandParameter="Home"/>
<Button Margin="10" Width="200" Content="Account" Command="{Binding UpdateViewCommand}" CommandParameter="Account"/>
</StackPanel>
在一个单独的类文件 (UpdateViewModel.cs) 中,UpdateViewModel 类实现了 Execute 方法,如下所示:
public void Execute (object parameter)
{
if (parameter.ToString() == "Home")
{
viewModel.SelectedViewModel = new HomeViewModel();
}
else if (parameter.ToString() == "Account")
{
viewModel.SelectedViewModel = new AccountViewModel();
}
}
我希望我已经给出了这个想法,而不会让你感到厌烦。这一切都有效,让我了解基础知识。现在我想尝试一种变体,即采用一个视图(“帐户”视图)并实现一个可以直接切换到另一个视图的按钮。我以为我要做的就是将按钮绑定到 UpdateViewModel 类,最初我修改了 Account.xaml 代码如下:
<Button Content="Button" Command="{Binding Path=UpdateViewCommand}" CommandParameter="Home"/>
程序运行,但是当我单击帐户视图中的按钮时,没有任何反应。所以我把它改成了更复杂的东西:
<UserControl.DataContext>
<src:MainViewModel/>
</UserControl.DataContext>
...
<Button Content="Button" Command="{Binding Path=UpdateViewCommand}" CommandParameter="Home"/>
但结果是一样的。我怀疑它与绑定有关,但看不到如何更改它。有人可以帮忙吗?
【问题讨论】: