我想从用户使用命令参数中的上下文菜单右键单击的 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/