44

I have set mouse events on a Canvas as follows:

<Canvas MouseUp="CanvasUp" MouseDown="CanvasDown" MouseMove="CanvasMove">
...
</Canvas>

But these are active only on the child elements like Image and Rectangle, not on the empty space. How can I solve this?

user279244
  • 961
  • 5
  • 18
  • 32

2 Answers2

98

A control with no background color set (explicitly or through styles etc) will default to having a background color of null - making it not hit-testable.

If you set the background to "Transparent" (or anything other than null ({x:Null})) then it will be able to pick up the mouse events

Rob Fonseca-Ensor
  • 15,510
  • 44
  • 57
  • 18
    Thanks for the answer, but what a STUPID design decision the WPF team did with that. – cdiggins Oct 04 '11 at 16:09
  • 1
    This advice is valuable a golden coin ! I'd rather default Canvas background to Transparent, rather than {x:null} as normally you'd expect event (with appropriate arguments) to fire when you click on canvas empty space. The default x:null behavior should be optionally settable, rather. – Sold Out May 18 '17 at 12:50
5

Set the background color. It defaults to null.

Use Background="White" for instance.

Pieniadz
  • 653
  • 3
  • 9
  • 22
Mark Synowiec
  • 5,385
  • 1
  • 22
  • 18