祖先级绑定在MenuItem命令中不起作用

本文关键字:命令 不起作用 MenuItem 绑定 祖先 | 更新日期: 2023-09-27 18:22:46

我们使用分层模板来填充菜单项

<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 中命令

祖先级绑定在MenuItem命令中不起作用

这种绑定方式:

{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MenuViewModel},     
                                        AncestorLevel=2, Mode=FindAncestor} 

不工作,因为AncestorType不是从UIElement派生的。

绑定的Path应该是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.AancestorType文档中,只说明理论上可以使用任何类型,但是,FindAncestor检查视觉树以尝试找到给定的祖先,因此无论您要查找的类型都必须存在于视觉树中。希望这能有所帮助。