C# 树状视图的选定项

C# 树状视图的选定项,c#,wpf,xaml,treeview,C#,Wpf,Xaml,Treeview,我想从树视图中获取selectedItem,用户使用命令参数中的上下文菜单右键单击该树视图。我不明白这里的相对来源应该是什么。请帮忙 <Grid.Resources> <HierarchicalDataTemplate x:Key="ChildTemplate" ItemsSource="{Binding Path=ChildSymbolList}" > <StackPanel Orientat

我想从树视图中获取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属性 获取或设置当ContextMenu打开时相对于其定位的UIElement


请分享您的
ItemTemplate
childtemplate我已经用有效的childtemplate更新了我的问题。非常感谢你。你能解释一下吗?实际上contextMenu不是同一个视觉树的一部分。所以在上下文菜单上找不到父级或祖先级。