【发布时间】:2015-10-19 13:18:45
【问题描述】:
我正在使用 MVVM 学习导航,如下所示:
在本教程中,为 button 控件绑定命令是通过使用 ItemsControl 实现的,如下所示:
<Window.Resources>
<DataTemplate DataType="{x:Type local:HomeViewModel}">
<local:HomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ProductsViewModel}">
<local:ProductsView />
</DataTemplate>
</Window.Resources>
<DockPanel>
<Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
<ItemsControl ItemsSource="{Binding PageViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"
Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding }"
Margin="2,5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
<ContentControl Content="{Binding CurrentPageViewModel}" />
</DockPanel>
如果我理解正确,它会遍历 PageViewModels 的集合并为每个 VIewModel 绑定一个按钮命令。此示例运行良好,我可以毫无问题地在页面之间切换。
但是,我不想迭代地创建按钮。我想在一个网格中有两个按钮,它们具有与上面示例一样切换视图的相同命令。像这样的:
<Window.Resources>
<DataTemplate DataType="{x:Type local:HomeViewModel}">
<local:HomeView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ProductsViewModel}">
<local:ProductsView />
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Content="{Binding HomeView.Name}"
Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding }"/>
<Button Grid.Column="1"
Content="{Binding ProductsView.Name}"
Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding }"/>
</Grid>
但这并不像我预期的那样工作。我可以绑定视图的名称,但不能绑定命令。单击按钮什么也不做。 DataContext 设置为我的 ApplicationViewModel 的一个实例。这里可能有什么问题?
【问题讨论】:
-
您是否尝试过将命令绑定更改为
{Binding ChangePageCommand...? -
是的。该按钮现已禁用,无法点击。