[英]How do I stop WPF KeyDown events from bubbling up from certain contained controls (such as TextBox)?
[英]Prevent KeyDown event bubbling from TextBox to MainWindow in WPF
我有一個包含文本框控件的程序。 用戶可以在此控件中輸入文本。 用戶還可以按某些鍵來觸發其他操作(這在MainWindow中處理)。 我有示例XAML和C#代碼來演示我的設置。
XAML
<Window x:Class="RoutedEventBubbling.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" />
<TextBox x:Name="Output" Grid.Row="1" IsReadOnly="True" />
</Grid>
</Window>
C#
using System.Windows;
using System.Windows.Input;
namespace RoutedEventBubbling
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private int mHitCount = 0;
public MainWindow()
{
InitializeComponent();
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
this.Output.Text = string.Format("Hit Count: {0}", ++mHitCount);
}
}
}
您可能已經意識到,在此程序中,如果我開始在第一個TextBox
鍵入內容,則第二個將使用命中計數進行更新。 這是不理想的結果,因為在處理MainWindow的OnKeyDown
方法時,我可能希望觸發某些動作。
因此,我的問題是這樣的:是否可以防止在MainWindow上調用OnKeyDown
方法,同時仍然允許將文本輸入到文本框中? 我知道e.Handled = true
方法,但是在這種情況下,對TextBox
的KeyDown
事件執行此操作將阻止輸入文本。 如果無法做到這一點,我將不得不尋找其他處理方式。
提前致謝。
編輯
我剛剛找到了解決此問題的適當方法。 如果我改為處理MainWindow的OnTextInput
方法,則將實現我所需的結果,因為將處理TextBox
的TextInput
事件。 以下是我使用的代碼示例:
private Key mPressedKey;
protected override void OnKeyDown(KeyEventArgs e)
{
// Note: This method will be called first.
base.OnKeyDown(e);
// Store the pressed key
mPressedKey = e.Key;
}
protected override void OnTextInput(TextCompositionEventArgs e)
{
// Note: This method will be called second, and only if the textbox hasn't handled it.
base.OnTextInput(e);
this.Output.Text = string.Format("Hit Count: {0}", ++mHitCount);
// ... Handle pressed key ...
}
您可以在該語句上放置基於類型的防護:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.OriginalSource is TextBoxBase == false)
{
mPressedKey = e.Key;
}
}
不過,可能也不是最好的解決方案。
我最終使用以下設置解決了這個問題:
private Key mPressedKey;
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
mPressedKey = e.Key;
}
protected override void OnTextInput(TextCompositionEventArgs e)
{
base.OnTextInput(e);
// ... Handle mPressedKey here ...
}
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
// Force focus back to main window
FocusManager.SetFocusedElement(this, this);
}
這是在MainWindow.xaml.cs中完成的。 這有點hack,但是達到了我想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.