Home > Enterprise >  e.Handled = true is not stopping keystroke event from bubbling up
e.Handled = true is not stopping keystroke event from bubbling up

Time:02-03

I have a TextBox contained inside a DockPanel. If Enter is pressed while typing in the TextBox, I want one thing to happen. If Enter is pressed elsewhere in the DockPanel, I want another thing to happen. What I don't want is for Both of the things to happen when Enter is pressed in the TextBox, but that's what's happening, even though I have e.Handled = true.

The pertinant XAML:

<DockPanel MinWidth="600" MinHeight="200" >
    <DockPanel.InputBindings>
        <KeyBinding Key="Return" Command="{Binding PlayCommand}" />
    </DockPanel.InputBindings>
    <Grid>
        <Grid.ColumnDefinitions ... >
        <Other Controls ...>
        <DockPanel Grid.Column="2">
            <Other Controls ...>
            <DockPanel DockPanel.Dock="Top">
                <Other Controls ...>
                <TextBox Name="txtFilterText" Text="{Binding SmartFilterText}" PreviewKeyUp="txtFilterText_PreviewKeyUp">
                </TextBox>
            </DockPanel>
        </DockPanel>
    </Grid>
</DockPanel>

The code-behind:

Private Sub txtFilterText_PreviewKeyUp(sender As Object, e As KeyEventArgs)
    ' when we hit Enter on the smart filter text box

    If e.Key = Key.Enter Then
        ' do the TextBox Enter stuff
        e.Handled = True
    End If
End Sub

When I press Enter in the TextBox, what happens is both the bound PlayCommand, and the PreviewKeyUp event handler run. I want only the PreviewKeyUp event handler code to run, and then stop there, and prevent the keyboard event from bubbling up to the PlayCommand on the containing DockPanel.

I've tried handling KeyUp instead of PreviewKeyUp, but it was the same.

I've tried putting e.Handled = True outside the If, but it was the same.

What is the correct way?

CodePudding user response:

Key bindings are invoked in response to key down messages, by the time the user physically releases the key the command handler has already long been invoked.

Ergo, intercept PreviewKeyDown instead.

  • Related