Search code examples
c#wpfmvvmuser-controlsinputbinding

How to differ click input between inside and outside of a UserControl?


(Please take each of controls stated below as control created using MVVM pattern)

So, I have a UserControl which I place on my MainWindow. I want my UserControl, if clicked (in the MainWindow, inside the UserControl), the background changed into another color, and if I click in the MainWindow, but outside of UserControl, then the UserControl's background will change to the original color.

What I've tried :

  1. I've tried to apply a Command inside the UserControl.InputBindings which to detect Mouse Input (MouseBinding), but the only MouseBinding raised is the MouseBinding in the Window.InputBindings (which should be raised ONLY when the click input is outside the UserControl), but apparently, wherever a click happen, the only MouseBinding raised is only the one in Window.InputBindings.
  2. Differ the CommandParameter between MouseBinding in Window.InputBindings and UserControl.InputBindings.

Question :

  1. How to differ the MouseBinding between clicking inside the UserControl and outside?

Thanks


Solution

  • The solution is simple. Just attach a PreviewMouseDown event handler to both the Window and the UserControl and handle both events in the Window:

    <Window ... PreviewMouseDown="Window_PreviewMouseDown">
        <UserControl Name="Control" PreviewMouseDown="UserControl_PreviewMouseDown" ... / >
    </Window>
    

    ...

    private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        Control.Background = someNewColourBrush;
    }
    
    
    private void UserControl_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        Control.Background = originalColourBrush;
    }