2
votes

I want to get selectedItem from the treeview on which the user right clicks using a context menu in a command parameter. I don't understand what should be the relative source here. Please help

        <Grid.Resources>
            <HierarchicalDataTemplate x:Key="ChildTemplate" ItemsSource="{Binding Path=ChildSymbolList}" >
                <StackPanel Orientation="Horizontal" Margin="2">
                    <TextBlock Text="{Binding Path=Name}" FontWeight="Bold">
                    </TextBlock>
                </StackPanel>
            </HierarchicalDataTemplate>
        </Grid.Resources>  

            <TreeView Name="Tree" ItemsSource="{Binding ItemList}" ItemTemplate="{StaticResource ChildTemplate}">
                <TreeView.ContextMenu>
                    <ContextMenu StaysOpen="true">
                        <MenuItem Header="MyMenu" Height="20" Command="{Binding RemoveMyCommand}" CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeView}}}">
                        </MenuItem>
                    </ContextMenu>
                </TreeView.ContextMenu>

            </TreeView>

I get an error

Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TreeView', AncestorLevel='1''.

1
please share your ItemTemplate ChildTemplateAbin
I have updated my question with the child templateJack Gray

1 Answers

2
votes

Try this:

 <MenuItem Header="MyMenu" Height="20" Command="{Binding RemoveMyCommand}" CommandParameter="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}">
                    </MenuItem>

ContextMenu.PlacementTarget Property

Gets or sets the UIElement relative to which the ContextMenu is positioned when it opens.