繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM