1
<DataTemplate DataType="{x:Type EntityType:FixedDevice}">
    <TextBlock Text="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource NameConverter}}"/>
</DataTemplate>

<TreeView.ItemContainerStyle>
    <Style TargetType="TreeViewItem">
        <EventSetter Event="PreviewMouseRightButtonUp" Handler="TreeViewItem_RightClick"/>
    </Style>
</TreeView.ItemContainerStyle>
<TreeViewItem Header="Data Warehouse">
    <TreeViewItem.Items>
        <TreeViewItem Header="Platforms">
            <TreeViewItem.Items>
                <TreeViewItem>
                    <TreeViewItem.Header>
                        <TextBlock Text="{Binding RelativeSource={RelativeSource Self},
                                   Path=Parent.Items.Count,
                                   StringFormat=Public ({0})}">
                        </TextBlock>
                    </TreeViewItem.Header>
                </TreeViewItem.Header>
            </TreeViewItem.Items>
        </TreeViewItem>
    </TreeViewItem.Items>
</TreeViewItem>

 private void TreeViewItem_RightClick(object sender, MouseButtonEventArgs e) {
      TreeViewItem item = sender as TreeViewItem;
      if(item != null) { item.Focus(); item.IsSelected = true; }
      e.Handled = true;
 }

为什么我右键单击时,它只选择最顶层的节点?而不是我点击的那个?与 a 类似ItemsSource,它Item本身不是 a TreeViewItem,而是DataTemplate带有 a 的 a TextBlock,如何在 TreeView 中直观地选择对象?

编辑,请参阅下面的基于@Viv 答案的答案。我最终不得不使用它e.OriginalSource来检索TextBlock当时的TreeViewItem那个Item

private void TreeViewItem_RightClick(object sender, MouseButtonEventArgs e) {
    TreeViewItem item = (e.OriginalSource as FrameworkElement).Parent as TreeViewItem;
    if(item == null) {
        item = e.Source as TreeViewItem;
        if(item == null) {
            return;
        }
    }
    item.IsSelected = true;
    e.Handled = true;
}
4

1 回答 1

1

这是因为你要找的是e.Source而不是sender

尝试将您的右键单击处理程序切换为:

private void TreeViewItem_RightClick(object sender, MouseButtonEventArgs e) {
  TreeViewItem item = e.Source as TreeViewItem;
  if (item == null)
    return;
  // item.Focus();
  item.IsSelected = true;
  e.Handled = true;
}

样本下载

于 2013-07-09T22:53:36.280 回答