c# - TreeView 的选定项目

标签 c# wpf xaml treeview

我想从用户使用命令参数中的上下文菜单右键单击的 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'' 进行绑定(bind)的源。

最佳答案

试试这个:

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

关于c# - TreeView 的选定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32010918/

相关文章:

c# - 将命令绑定(bind)到 DataGrid 中的元素

wpf - 带有命令绑定(bind)的 KeyBinding 不适用于 TextBox UpdateSourceTrigger LostFocus

javascript - C# 中是否有一个knockoutjs 计算等效项?

wpf - 在 WPF 中递归捕获所有 Click 或 Touch 事件

c# - 如何修复 "a connection attempt failed because the connected party did not properly respond after a period of time ..."错误?

c# - XAML 继承、代码重用、优化

XAML/C# : What event fires after reordering a gridview?

Silverlight:滚动查看器仅在内容溢出时出现?

c# - 在哪里可以找到 "Microsoft.VisualStudio.TestTools.UnitTesting"丢失的 dll?

c# - MySQL 表名作为参数