Friday, April 15, 2011

In WPF, how can I cancel the keypress after processing it with PreviewKeyDown?

In my WPF Datagrid I capture the "delete" key, process it, and then the datagrid itself deletes the row from the UI by continuing to process its own handler for the delete key (which is what I want).

But now I want CTRL-S to open up a search bar, which it does, but it also goes on to blank out the cell the user was on when he pressed CTRL-S, so I am looking for a way to tell the datagrid to cancel the key press so that it is not executed on the Datagrid.

How can I cancel a keypress like this?

XAML:

<toolkit:DataGrid x:Name="TheDataGrid" DockPanel.Dock="Bottom"
                  CanUserAddRows="False"
                  AlternatingRowBackground="#ddd"
                  CanUserSortColumns="true"
                  PreviewKeyDown="TheDataGrid_PreviewKeyDown"
                  AutoGenerateColumns="False"
                  RowEditEnding="TheDataGrid_RowEditEnding">

code-behind:

private void TheDataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.S))
    {
        ShowSearchBar();
    }

    switch (e.Key)
    {
        case Key.Delete:
            DeleteCustomer(sender, e);
            break;
    }
}
From stackoverflow
  • e.Handled = true;
    
  • In a slightly different situation, I have a second argument of type PreviewKeyDownEventArgs, in which situation the solution is:

    e.IsInputKey = true;
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.