问题描述
我的应用程序使用TreeView
填充了TreeView.ItemTemplate
中定义的自定义节点。每个节点的内容都通过StackPanel
事件包装到Node_ContexMenuopening
中,该事件根据正在运行的某些应用程序属性填充上下文菜单。
XAML:
<TreeView x:Name="treeNodes" ContextMenu="{StaticResource EmptyContextMenu}" ContextMenuopening="TreeNodes_ContextMenuopening">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type c:MyCustomType}" ItemsSource="{Binding MyCustomTypeChildren}">
<StackPanel Orientation="Horizontal" ContextMenu="{StaticResource EmptyContextMenu}" ContextMenuopening="Node_ContextMenuopening" >
<Image Source="Frontend\Images\import.png" MaxWidth="15" MaxHeight="15"/>
<TextBlock Width="5"/>
<TextBlock Text="{Binding CustomTypeName}" MinWidth="100"/>
<TextBlock Width="10"/>
<Image Source="CustomImagePath" MaxWidth="15" MaxHeight="15"/>
<TextBlock Width="5"/>
<TextBlock Text="{Binding CustomTypeName2}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
后面的代码:
private void Node_ContextMenuopening(object sender,ContextMenuEventArgs e)
{
FrameworkElement fe = sender as FrameworkElement;
// get context menu and clear all items (empty menu with single placeholder item
// is assigned in XAML to prevent "no object instance" exception)
ContextMenu menu = fe.ContextMenu;
menu.Items.Clear();
// populate menu there
}
我想在TreeView上具有相同的功能(右键单击Treeview的空白区域时,Treeview特定的上下文菜单),
private void TreeNodes_ContextMenuopening(object sender,ContextMenuEventArgs e)
{
TreeView tw = sender as TreeView;
ContextMenu menu = tw.ContextMenu;
menu.Items.Clear();
// poopulate menu there
}
但是问题是,即使在处理TreeNodes_ContextMenuopening
之后,右键单击TreeView节点后,也会触发Node_ContextMenuopening
,这将覆盖被单击节点的上下文菜单。我尝试使用以下方法解决它:
// also tried IsMouSEOver and IsMouseCaptureWithin
if (tw.IsMouseDirectlyOver)
{
// handle TreeNodes_ContextMenuopening event there
}
但没有成功。有什么建议? 预先感谢。
解决方法
您可以尝试使用ContextMenuEventArgs.Handled
值。 https://docs.microsoft.com/en-us/dotnet/api/system.windows.routedeventargs.handled?view=netcore-3.1#System_Windows_RoutedEventArgs_Handled
获取或设置一个值,该值指示路由事件在路径中传播时事件处理的当前状态。
示例
protected override void OnPreviewMouseRightButtonDown(System.Windows.Input.MouseButtonEventArgs e)
{
e.Handled = true; //suppress the click event and other leftmousebuttondown responders
MyEditContainer ec = (MyEditContainer)e.Source;
if (ec.EditState)
{ ec.EditState = false; }
else
{ ec.EditState = true; }
base.OnPreviewMouseRightButtonDown(e);
}