C# – WPF: OnKeyDown() not being called for space key in control derived from WPF TextBox

conkeydowntextboxwpf

In a WPF application, I have a control that I have derived from TextBox like this:

public class SelectableTextBlock : TextBox
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        e.Handled = false;
    }
}

The OnKeyDown method is not called when entering a space into the TextBox, nor when hitting Backspace, but does fire for other input including normal printable characters (e.g. 'a') and modifier keys (e.g. ).

I'm using this control with IsReadOnly set to true so I can display selectable, uneditable text. The control used within WPFToolkit's DataGrid, and I want KeyDown events to propagate up the data grid, even if the SelectableTextBlock has focus, which is why I am using a custom control to explicitly mark the event as unhandled.

The problem is that the event isn't even making it to my control for certain keys. I can't just use OnPreviewKeyDown in the DataGrid to get round this, since I do want other controls used in the data grid to swallow the space KeyDown event.

Does anyone know how I can get the KeyDown event for the space key to propagate up?

Thanks.

Best Answer

The PreviewKeyDown event exists exactly for this sort of thing.

private void spacebarHandler_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Space)
        e.Handled = true;
}

Your KeyDown handler will never receive the KeyDown event for spacebar.

Related Topic