【发布时间】:2012-07-16 22:10:03
【问题描述】:
是否可以将上下文菜单附加到 wpf 控件并在左键单击时打开它(而不是更习惯的右键单击)?我想仅使用 xaml 来实现(这应该是我的控件视图模板的一部分)。
【问题讨论】:
标签: c# wpf user-interface contextmenu
是否可以将上下文菜单附加到 wpf 控件并在左键单击时打开它(而不是更习惯的右键单击)?我想仅使用 xaml 来实现(这应该是我的控件视图模板的一部分)。
【问题讨论】:
标签: c# wpf user-interface contextmenu
这是一种在左键单击时显示上下文菜单的方法:
在Border 元素上创建一个新的左键处理程序:
<Border x:Name="Win"
Width="40"
Height="40"
Background="Purple"
MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp">
然后添加:
private void UIElement_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
var mouseDownEvent =
new MouseButtonEventArgs(Mouse.PrimaryDevice,
Environment.TickCount,
MouseButton.Right)
{
RoutedEvent = Mouse.MouseUpEvent,
Source = Win,
};
InputManager.Current.ProcessInput(mouseDownEvent);
}
它的作用,它基本上将左键单击映射到右键单击。为了可重用性,您可以将其包装到附加的行为中。
【讨论】:
下面是我建议的一个简单示例:
XAML:
<Window x:Class="LeftClickMenu.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<Grid>
<Border Width="400" Height="300" Background="#ccc" BorderBrush="#333"
BorderThickness="1"
MouseLeftButtonDown="Border_MouseLeftButtonDown"
MouseRightButtonUp="Border_MouseRightButtonUp">
<Border.ContextMenu>
<ContextMenu x:Name="myContextMenu">
<MenuItem Header="Menu Item 1" />
<MenuItem Header="Menu Item 2" />
<MenuItem Header="Menu Item 3" />
<MenuItem Header="Menu Item 4" />
<MenuItem Header="Menu Item 5" />
</ContextMenu>
</Border.ContextMenu>
</Border>
</Grid>
</Window>
还有代码隐藏:
using System.Windows;
using System.Windows.Input;
namespace LeftClickMenu
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
myContextMenu.IsOpen = true;
}
private void Border_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
}
}
我还添加了额外的 MouseRightButtonUp 事件来禁止右键单击上下文菜单弹出。
【讨论】:
创建一个以编程方式打开子菜单的方法,如这篇 SO 文章中所述: Show menu programmatically in WPF
为 LeftMouseButtonDown 创建一个事件并在 XAML 中调用该事件。
【讨论】: