Ancestor level binding not working in MenuItem command

1.7k Views Asked by At

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

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

1

There are 1 best solutions below

0
On

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.

The Path of the binding should be DataContext.MenuClick, and the AncestorType should be 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.

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. Hope this helps.