[英]Ancestor level binding not working in MenuItem command
我們使用分層模板填充菜單項
<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>
在這種情況下,我嘗試將MenuClick(ICommand)綁定到MenuItem,但未正確綁定
我已經在以下論壇鏈接中檢查了綁定
[http://stackoverflow.com/questions/23941314/wpf-how-can-i-create-menu-and-submenus-using-binding?rq=1][1]
在MenuModel中添加的該命令中,我需要在MenuViewmodel中進行Command
這種綁定方式:
{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MenuViewModel},
AncestorLevel=2, Mode=FindAncestor}
..不起作用,因為AncestorType
不是從UIElement
派生的。
綁定的路徑應為DataContext.MenuClick
,而AncestorType
應為Menu
。 全部放在一起:
<Setter Property="Command"
Value="{Binding Path=DataContext.MenuClick,
RelativeSource={RelativeSource AncestorType={x:Type Menu},
AncestorLevel=2}}">
</Setter>
Mode=FindAncestor
是默認模式,因此我將其省略。
在MSDN:RelativeSource.AncestorType文檔中 ,僅說明了理論上可以使用任何類型,但是, FindAncestor
檢查可視化樹以嘗試找到給定的祖先,因此您要查找的任何類型都必須存在於可視化樹中。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.