问题描述
我的应用中有菜单.我正在使用分层数据模板对其进行可视化:
I have Menu in my app. I'm visualizing it using hierarchical data template:
<MenuItem Header="Main menu" ItemsSource="{Binding ApplicationMenu}" >
<MenuItem.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type tm:RMenuItem}"
ItemsSource="{Binding Path=ChildrenItems}">
<MenuItem Header="{Binding Name}" Command="{Binding RunOperationCommand}" />
</HierarchicalDataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
菜单看起来像它应该的那样,但是每个菜单项的命令都没有被触发!更重要的是 - 它没有界限,这可以在调试器中看到:从未执行过获取 ICommand 属性的访问器.为什么会这样?
menu looks like as it should, but Command for each menu item is not fired! Even more - it is not bounded, which could be seen in debugger: get accessor of ICommand Property has been never executed. Why it happens so?
像往常一样完美:
<Menu>
<MenuItem Header="SomeHeader" Command="{Binding RunOperationCommand}"/>
<Menu>
推荐答案
您问题中第一个和第二个示例之间的区别在于,在第二个代码段中,您将 MenuItem.Command
绑定到父级的数据上下文,其中定义了 RunOperationCommand
.而在使用 HierarchicalDataTemplate
的第一个示例中,您将绑定到本地"DataContext,这是一个菜单项.它没有适当的属性,所以绑定失败.
The difference between the first and the second example in your question is that in the second code snippet you are binding MenuItem.Command
to the parent's data context, which has the RunOperationCommand
defined. Whereas in the first example with the HierarchicalDataTemplate
you are binding to the "local" DataContext, which is a menu item. It doesn't have the appropriate property, so the binding fails.
您有多种选择:
- 一种是使用命令属性扩展您的菜单项,就像您在回答中所做的那样;
- 绑定到可视化树中的相对源,它具有命令的数据上下文,例如假设命令在您窗口的 DataContext 中:
<MenuItem Header="Main menu" ItemsSource="{Binding ApplicationMenu}" >
<MenuItem.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type tm:RMenuItem}"
ItemsSource="{Binding Path=ChildrenItems}">
<MenuItem Header="{Binding Name}"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.RunOperationCommand}"
/>
</HierarchicalDataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
<小时>
- 从你的命令中创建一个静态资源,类似于 这篇博文接近
<Window.Resources>
<coreView:CommandReference x:Key="RunOperationCommand"
Command="{Binding RunOperationCommand}" />
</Window.Resources>
<MenuItem Header="Main menu" ItemsSource="{Binding ApplicationMenu}" >
<MenuItem.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type tm:RMenuItem}"
ItemsSource="{Binding Path=ChildrenItems}">
<MenuItem Header="{Binding Name}"
Command="{StaticResource RunOperationCommand}"
/>
</HierarchicalDataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
这篇关于分层数据模板中的命令绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!