带有ItemsSource的TreeViewItem右键单击不会选择Item

时间:2013-07-09 20:36:31

标签: wpf xaml treeview selecteditem

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

为什么我右键单击它,它只选择最顶层的节点?而不是我点击的那个?类似于ItemsSource Item本身不是TreeViewItem,而DataTemplate具有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;
}

1 个答案:

答案 0 :(得分: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;
}

Sample Download