【问题标题】:Ancestor level binding not working in MenuItem command祖先级绑定在 MenuItem 命令中不起作用
【发布时间】:2014-09-19 06:32:09
【问题描述】:

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

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

【问题讨论】:

    标签: c# wpf binding icommand findancestor


    【解决方案1】:

    这种绑定方式:

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

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

    绑定的路径应该是DataContext.MenuClickAncestorType应该是Menu。把它们放在一起:

    <Setter Property="Command" 
            Value="{Binding Path=DataContext.MenuClick, 
                            RelativeSource={RelativeSource AncestorType={x:Type Menu},
                                                           AncestorLevel=2}}">
    </Setter>
    

    Mode=FindAncestor 是默认模式,所以我省略了。

    MSDN: RelativeSource.AncestorType Documentation 中仅声明理论上可以使用任何类型,但是,FindAncestor 检查视觉树以尝试找到给定的祖先,因此您要查找的任何类型都必须存在于视觉中树。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-04-28
      • 2015-04-07
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      相关资源
      最近更新 更多