(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 :
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
.CommandParameter
between MouseBinding
in Window.InputBindings
and UserControl.InputBindings
.Question :
MouseBinding
between clicking inside the UserControl
and outside?Thanks
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;
}