0

(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

Moses Aprico
  • 1,951
  • 5
  • 30
  • 53

1 Answers1

1

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;
}
Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • Ha... yeah, I normally go for the simplest solution these days, not the best. I've often found that when I roll out the big guns and suggest a great solution, I just end up having to answer a million comments asking further questions and I just don't have the time (or patience) to do that anymore. – Sheridan Jun 23 '14 at 16:23
  • This is correct, but I am trying to do "the right MVVM" way. – Moses Aprico Jun 23 '14 at 16:33
  • 1
    @MosesAprico to clarify, this solution does not "break" MVVM, because it uses code behind for UI-specific purposes, which is OK. – Federico Berasategui Jun 23 '14 at 16:46
  • 1
    I'd agree with @HighCore here. This is purely UI related and so not needed in the view model. However, when you *do* need to handle an event in the view model, you can wrap it up in an Attached Property. See my answer to the [What's the best way to pass event to ViewModel?](http://stackoverflow.com/questions/21285577/whats-the-best-way-to-pass-event-to-viewmodel/21285863#21285863) question to see how it's done. – Sheridan Jun 23 '14 at 18:16