Dork
Dork

Reputation: 1886

right way to stop keydown event from bubble up

Here I have window which need to handle different keys in keydown event. When Enter is pressed popup with textbox emerges and text typed into this textbox SHOULD NOT raise window keydown event.

<Window x:Class="PopupTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:PopupTest"
    mc:Ignorable="d"
    Title="MainWindow"
    Height="350"
    Width="525"
    KeyDown="Window_KeyDown"  >
<Grid>
    <Popup Name="symbolPopup"
           Grid.Row="0"
           Placement="RelativePoint"
           IsOpen="False">
        <TextBox Width="70" x:Name="symbolTextBox"
                 KeyDown="symbolTextBox_KeyDown"
                 Background="#FFFFDF18" />

    </Popup>
</Grid>

Code behind:

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.Enter:
                {
                    symbolPopup.IsOpen = true;
                    symbolTextBox.Focus();
                    break;
                }
            default:
                break;
        }
    }

    private void symbolTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            symbolPopup.IsOpen = false;
            string name = symbolTextBox.Text;
            symbolTextBox.Text = null;
            e.Handled = true;
            MessageBox.Show(name + " assigned");
        }
        // e.Handled = true;
    }

I don't need window keydown event to fire while popup is opened. If I uncomment //e.Handled = true textbox wouldn't get any text at all. I know I can solve this by checking if popup is open in the body of window keydown handler, but my question is how can I stop keydown to buble up from textbox and same time making textbox get what user types?

Upvotes: 2

Views: 1964

Answers (1)

MikeT
MikeT

Reputation: 5500

you can't stop the event firing you just need to be smarter in your handling

eg have you considered switching events to the preview event? What are WPF Preview Events?

or failing that you could set the handled based on the value of the popups Visibility

so in the window event handler

if(popup.Visibility == Visibility.Visible)
{
    //ignore event
}
else
{
   //handle window processing
   e.Handled = true;
}

remember that e.Handled = true cancels the bubbling/tunnelling process so should only be set when your sure nothing else want to handle the event

Upvotes: 0

Related Questions