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

后端 未结 4 1793
谎友^
谎友^ 2020-12-06 00:39

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

public class SelectableTextBlock : TextBox
{
    protected override void O         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 01:21

    Derive a say, RestrictKeysTextBox from TextBox.

    public class RestrictKeysTextBox : TextBox
    {
        ....
    }
    

    Override the OnPreviewKeyDown event in the RestrictKeysTextBox.

    Put logic in this override like this:

    if (e.Key == Key.Space)
    {
        e.Handled = true;
    }
    

    Bind the instance of the RestrictKeysTextBox to your DataGrid.

    That should work without overriding the OnPreviewKeyDown in the DataGrid and eliminate the associated problems.

提交回复
热议问题