C# 在WPF中防止从文本框到主窗口的KeyDown事件冒泡

C# 在WPF中防止从文本框到主窗口的KeyDown事件冒泡,c#,wpf,event-bubbling,event-routing,C#,Wpf,Event Bubbling,Event Routing,我有一个包含文本框控件的程序。用户可以在此控件中输入文本。用户还可以按某些键触发其他操作(这在主窗口中处理)。我有示例XAML和C#代码来演示我的设置 XAML <Window x:Class="RoutedEventBubbling.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.c

我有一个包含文本框控件的程序。用户可以在此控件中输入文本。用户还可以按某些键触发其他操作(这在主窗口中处理)。我有示例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>

您可以将基于类型的保护放在该语句上:

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中完成的。这有点像黑客,但它达到了我想要的效果。

为什么不使用这种方法呢?我刚试过,它阻止我在文本框中键入内容。哦,没想到,真不幸。e.Handled=true;不行吗?
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);
}