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