How can a control handle a Mouse click outside of that control? How can a control handle a Mouse click outside of that control? wpf wpf

How can a control handle a Mouse click outside of that control?


Just to clarify the answer provided about mouse focus - it was useful but I had to do some further digging + mucking about to get something that actually worked:

I was trying to implement something like a combobox and needed similar behaviour - to get the drop down to disapear when clicking on something else, without the control having knowledge of what something else was.

I had the following event for a drop down button:

    private void ClickButton(object sender, RoutedEventArgs routedEventArgs)    {        //do stuff (eg activate drop down)        Mouse.Capture(this, CaptureMode.SubTree);        AddHandler();    }

The CaptureMode.SubTree means you only get events that are outside the control and any mouse activity in the control is passed through to things as normal. You dont have the option to provide this Enum in UIElement's CaptureMouse, this means you will get calls to HandleClickOutsideOfControl INSTEAD of calls to any child controls or other handlers within the control. This is the case even if you dont subscribe to the events they are using - full Mouse capture is a bit too much!

    private void AddHandler()    {        AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseButtonEventHandler(HandleClickOutsideOfControl), true);    }

You would also need to hang on to + remove the handler at the appropriate points but I've left that out here for the sake of clarity/brevity.

Finally in the handler you need to release the capture again.

    private void HandleClickOutsideOfControl(object sender, MouseButtonEventArgs e)    {        //do stuff (eg close drop down)        ReleaseMouseCapture();    }


Capture the mouse. When an object captures the mouse, all mouse related events are treated as if the object with mouse capture perform the event, even if the mouse pointer is over another object.


I usually get the parent window and add a preview handler, even if already handled. Sometimes when MouseCapture is not enough, this technique comes handy:

Window.GetWindow(this).AddHandler(    UIElement.MouseDownEvent,    (MouseButtonEventHandler)TextBox_PreviewMouseDown,    true);