Search code examples
wpfinputbinding

PreviewMouseLeftButtonDown and InputBindings relationship


Using .NET 4.5.1 on Windows 8.1 Pro. In my UserControl I have grid. I need to preview and handle mouse events in this grid. So I override the PreviewMouseLeftButtonDown event:

    myGrid.PreviewMouseLeftButtonDown +=
        new MouseButtonEventHandler(myGrid_PreviewLeftButtonDown);
}

private void myGrid_PreviewLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    // ...
    e.Handled = true; // <-- IMPORTANT!
}

My UserControl also has a few InputBindings that are being registered in the static constructor. E.g.:

CommandManager.RegisterClassInputBinding(typeof(MyUserControl),
    new KeyBinding(MyCommands.SelectAll, new KeyGesture(Key.A, ModifierKeys.Control)));

InputBinding dependent on PreviewMouseLeftButtonDown?!

Now, when I set e.Handled to true in my PreviewMouseLeftButtonDown handler, my InputBindings stop working! Why?! I cannot understand how the mouse handler is linked to my keyboard shortcuts!


Solution

  • The only reason I can come up now is the following: you register input binding to MyUserControl, therefore for it to activate this UserControl has to have focus. When you make mouse event handled on Grid level, you don't allow this input to go to UserControl. So, no input - no focus, no focus - no command activation.

    Let's say we change the code a bit:

    private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        e.Handled = true;
        FocusManager.SetFocusedElement(this, myUC);
    }
    

    Where myUC is our UserControl. But UserControl is not focusable, so we'll add a little focus transfer inside it:

    protected override void OnGotFocus(RoutedEventArgs e)
    {
        btn.Focus();
        base.OnGotFocus(e);
    }
    

    Where btn us just some empty Button or whatever focusable element you like. Then it works ok.

    So, my take on the problem is: the reason is not in mouse events, it's in focus.