【问题标题】:WPF - Open ContextMenu on left mouse hold downWPF - 按住鼠标左键打开 ContextMenu
【发布时间】:2011-02-25 11:41:35
【问题描述】:

在 Google Chrome 中,我非常喜欢鼠标左键按住“后退”按钮以获取完整浏览历史记录的功能。

在我的 WPF 应用程序中:对于带有上下文菜单的按钮,如何在按住鼠标左键的情况下打开菜单(当然仍然是常规的右键单击)?

【问题讨论】:

标签: .net wpf contextmenu onmousedown


【解决方案1】:

我建议通过在那里启动一个计时器来处理MouseDown 事件。如果触发了MouseUp 事件,则需要停止计时器。您可以为此使用DispatcherTimer。然后您可以设置一个时间,之后应该触发Timer_Tick 事件,您可以在其中执行您想要执行的操作。为了避免冒泡 MouseDownMouseUp 事件出现问题,我建议在窗口构造函数中添加两个处理程序,而不是在 XAML 中添加它们(至少在我的示例代码中事件没有触发,所以我改变了)通过使用

button1.AddHandler(FrameworkElement.MouseDownEvent, new MouseButtonEventHandler(button1_MouseDown), true);
button1.AddHandler(FrameworkElement.MouseUpEvent, new MouseButtonEventHandler(button1_MouseUp), true);

另外,你需要在那里设置定时器:

在窗口类中添加一个字段:

DispatcherTimer timer = new DispatcherTimer();

并使用您想要等待的时间设置计时器,直到Timer_Tick 事件被触发(也在窗口构造函数中):

timer.Tick += new EventHandler(timer_Tick);
// time until Tick event is fired
timer.Interval = new TimeSpan(0, 0, 1);

那么你只需要处理事件就完成了:

private void button1_MouseDown(object sender, MouseButtonEventArgs e) {
    timer.Start();
}

private void button1_MouseUp(object sender, MouseButtonEventArgs e) {
    timer.Stop();
}

void timer_Tick(object sender, EventArgs e) {
    timer.Stop();
    // perform certain action
}

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    我认为您唯一的方法是在按钮上手动处理 MouseDown/Move/Up 事件,在 MouseDown 发生后等待一段时间过去,如果在这段时间内您没有 MouseMove 或 MouseUp事件,然后手动显示 ContextMenu。如果您显示上下文菜单,则必须注意按钮不要在此之后生成 Click 事件,并执行默认的单击操作。

    【讨论】:

      猜你喜欢
      • 2011-09-20
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多