テキスト ボックス コントロールを含むプログラムがあります。ユーザーは、このコントロールにテキストを入力できます。ユーザーは、特定のキーを押して他のアクションをトリガーすることもできます (これは 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
のプログラムに入力を開始すると、2 番目のプログラムのヒット カウントが更新されます。OnKeyDown
MainWindow のメソッドを処理するときにトリガーしたい特定のアクションがある可能性があるため、これは望ましくない結果です。
OnKeyDown
そのため、私の質問は次のとおりです。テキスト ボックスにテキストを入力できるようにしながら、MainWindow でメソッドが呼び出されるのを防ぐことは可能ですか? 私はe.Handled = true
アプローチを知っていますが、この場合、KeyDown
イベントでそれTextBox
を行うと、テキストが入力されなくなります。これが不可能な場合は、すべてを処理する別の方法を見つける必要があります。
前もって感謝します。
編集
この問題を回避する適度にハックな方法を見つけました。代わりにMainWindow のOnTextInput
メソッドを処理するTextInput
と、意志のイベントTextBox
が処理されるため、目的の結果が得られます。以下は、私が使用したコードのサンプルです。
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 ...
}