You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MahApps.Metro时KeyUp事件触发两次的问题求助

Fix: KeyUp Event Firing Twice in MahApps.Metro WPF Project

I’ve dug into your issue where the KeyUp event on a TextBox fires twice in your MahApps.Metro WPF project. Here’s the breakdown of what’s causing it and how to fix it:

Why This Happens

The double-trigger typically comes from one of two scenarios with MahApps.Metro:

  1. Focus Interference from ShowMessageAsync: When you call ShowMessageAsync directly in the KeyUp handler, this async dialog steals focus from the TextBox. This sudden focus shift can trigger an extra keyboard event as the control loses focus.
  2. Event Routing in Metro Templates: MahApps.Metro’s MetroWindow or styled TextBox may have nested elements in their control templates, causing the KeyUp event to bubble/tunnel through multiple elements and get captured twice.

Solutions

1. Mark the Event as Handled

Prevent the event from propagating further up the visual tree by setting e.Handled = true in your handler. This stops any other elements from catching the same event:

private void Textbox_KeyUp(object sender, KeyEventArgs e)
{
    // Stop the event from being processed again
    e.Handled = true;

    if (!string.IsNullOrEmpty(textbox.Text))
    {
        this.ShowMessageAsync("This is the title", "Some message");
    }
}

2. Delay the Dialog to Avoid Focus Issues

Since the dialog is causing a focus shift, use the Dispatcher to delay its execution until after the KeyUp event has fully processed:

private void Textbox_KeyUp(object sender, KeyEventArgs e)
{
    if (!string.IsNullOrEmpty(textbox.Text))
    {
        // Run the dialog after the current event cycle completes
        Dispatcher.InvokeAsync(() =>
        {
            this.ShowMessageAsync("This is the title", "Some message");
        });
    }
}

3. Check for Duplicate Event Bindings

Double-check your XAML and code-behind to make sure you haven’t registered the KeyUp event twice. For example, if you have both <TextBox KeyUp="Textbox_KeyUp"/> in XAML and textbox.KeyUp += Textbox_KeyUp; in code, the handler will run twice.

How to Verify the Root Cause

To confirm what’s driving the double trigger:

  • Temporarily comment out the ShowMessageAsync call. If the event only fires once, the dialog’s focus shift is the issue.
  • If it still fires twice, test swapping MetroWindow for a standard WPF Window. If the problem goes away, it’s related to MahApps’ control template routing.

Content sourced from Stack Exchange, question author: Matheus Miranda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:56:30