Treeview 的选定项目

Selected Item of Treeview

我想从用户使用命令参数中的上下文菜单右键单击的树视图中获取 selectedItem。我不明白这里的相对来源应该是什么。请帮忙

        <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>

我收到一个错误

找不到与参考“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.TreeView',AncestorLevel='1'”绑定的源。

试试这个:

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

ContextMenu.PlacementTarget 属性

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