n0win0u
n0win0u

Reputation: 45

How to bind command into a context menu that is inside TreeView on it's items?

I want to be able to execute a command on an item inside the TreeView by clicking the command in the context menu. And to be more specific only if the item is of a certain type (the xxTreeViewItem is an interface with 2 subtypes).

   <Grid Name="Root" commonExtensions:EnterKeyUpdateExtension.IsEnabled="True">

    <StackPanel Orientation="Vertical" Grid.Row="0">
        <Button Content="Center on" Command="{Binding Path=CenterOnCommand}" Margin="5,10,5,0"/>
    </StackPanel>
        <Grid>
            <TreeView Grid.Row="0" Name="xxTreeView" DataContext="{Binding Path=xxViewModel}" ItemsSource="{Binding Path=Items}">
                <TreeView.ItemContainerStyle>
                    <Style TargetType="{x:Type TreeViewItem}">
                        <Setter Property="ContextMenu">
                            <Setter.Value>
                                <ContextMenu>
                                    <MenuItem Header="Center On" Command="{Binding CenterOnCommand}"/>
                                </ContextMenu>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TreeView.ItemContainerStyle>
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding Path=Items}" DataType="{x:Type localViewItems:xxTreeViewItem}">
                        <TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
            </TreeView>

The Command in the button on the top works, but it does not work below in the context menu. I tried several bindings and finding of the ancestor but none of it works. Is there XAML only solution?

Upvotes: 1

Views: 879

Answers (1)

Il Vic
Il Vic

Reputation: 5666

The ContextMenu does not belong to the visual tree, so it does not inherit your TreeView's DataContext. So you need to pass it to your ContextMenu by using the PlacementTarget property:

<TreeView.ItemContainerStyle>
    <Style TargetType="{x:Type TreeViewItem}">
        <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=TreeView}, Path=DataContext}"></Setter>
        <Setter Property="ContextMenu">
            <Setter.Value>
                <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                    <MenuItem Header="Center On" Command="{Binding CenterOnCommand}" />
                </ContextMenu>
            </Setter.Value>
        </Setter>
    </Style>
</TreeView.ItemContainerStyle>

I hope it can help you

Upvotes: 2

Related Questions