使用MahApps.Metro时KeyUp事件触发两次的问题求助
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:
- Focus Interference from
ShowMessageAsync: When you callShowMessageAsyncdirectly in theKeyUphandler, this async dialog steals focus from the TextBox. This sudden focus shift can trigger an extra keyboard event as the control loses focus. - Event Routing in Metro Templates: MahApps.Metro’s
MetroWindowor styled TextBox may have nested elements in their control templates, causing theKeyUpevent 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
ShowMessageAsynccall. If the event only fires once, the dialog’s focus shift is the issue. - If it still fires twice, test swapping
MetroWindowfor a standard WPFWindow. If the problem goes away, it’s related to MahApps’ control template routing.
Content sourced from Stack Exchange, question author: Matheus Miranda

