分层数据模板中的命令绑定

编程入门 行业动态 更新时间:2024-10-28 02:27:14
本文介绍了分层数据模板中的命令绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的应用中有菜单.我正在使用分层数据模板对其进行可视化:

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>

更多推荐

分层数据模板中的命令绑定

本文发布于:2023-10-19 07:16:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1506771.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   命令   模板   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!