![](/img/trans.png)
[英]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.