[英]Ancestor level binding not working in MenuItem command
We have use the hierarchical template to populate the menuitem 我们使用分层模板填充菜单项
<UserControl.DataContext>
<local:MenuViewModel/>
</UserControl.DataContext>
<Grid>
<!--Initialize the Menu-->
<Menu Name="Part_Menu" ItemsSource="{Binding MenuCollection}" Background="#E5E5E5" VerticalAlignment="Center">
<Menu.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding MenuItemCollection}">
<TextBlock Text="{Binding Header}" />
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="CommandParameter" Value="{Binding Header}"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Command"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MenuViewModel}, AncestorLevel=2,Mode=FindAncestor},Path=MenuClick}"></Setter>
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>
</HierarchicalDataTemplate>
</Menu.ItemTemplate>
</Menu>
</Grid>
In this i have tried to bind the MenuClick(ICommand) to MenuItem , but it did not bind correctly 在这种情况下,我尝试将MenuClick(ICommand)绑定到MenuItem,但未正确绑定
I have check the binding in the following forum link 我已经在以下论坛链接中检查了绑定
[http://stackoverflow.com/questions/23941314/wpf-how-can-i-create-menu-and-submenus-using-binding?rq=1][1]
In this command added in the MenuModel , i need to Command in the MenuViewmodel 在MenuModel中添加的该命令中,我需要在MenuViewmodel中进行Command
This way of binding : 这种绑定方式:
{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MenuViewModel},
AncestorLevel=2, Mode=FindAncestor}
..is not working, because the AncestorType
does not derive from UIElement
. ..不起作用,因为
AncestorType
不是从UIElement
派生的。
The Path of the binding should be DataContext.MenuClick
, and the AncestorType
should be Menu
. 绑定的路径应为
DataContext.MenuClick
,而AncestorType
应为Menu
。 Putting it all together : 全部放在一起:
<Setter Property="Command"
Value="{Binding Path=DataContext.MenuClick,
RelativeSource={RelativeSource AncestorType={x:Type Menu},
AncestorLevel=2}}">
</Setter>
Mode=FindAncestor
is the default mode, so i left that out. Mode=FindAncestor
是默认模式,因此我将其省略。
In the MSDN: RelativeSource.AncestorType Documentation it is only stated that any Type could theoretically be used, however, FindAncestor
inspects the visual tree to try and find the given ancestor, so whatever type you are looking for must be present in the visual tree. 在MSDN:RelativeSource.AncestorType文档中 ,仅说明了理论上可以使用任何类型,但是,
FindAncestor
检查可视化树以尝试找到给定的祖先,因此您要查找的任何类型都必须存在于可视化树中。 Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.