Why doesn't this WPF code generate a context menu?
Asked Answered
S

1

7

Perhaps I'm having a Post-Ballmer-Peak Moment. I'm hoping that someone can help point out the obvious to me.

Why does this code generate a context menu on right click:

<Canvas Background="Transparent">
  <Canvas.ContextMenu>
    <ContextMenu>
      <TextBlock>WTF?</TextBlock>
    </ContextMenu>
  </Canvas.ContextMenu>
</Canvas>

And this code doesn't generate a context menu:

<Canvas>
  <Canvas.ContextMenu>
    <ContextMenu>
      <TextBlock>WTF?</TextBlock>
    </ContextMenu>
  </Canvas.ContextMenu>
</Canvas>
Showmanship answered 16/5, 2009 at 3:27 Comment(1)
WTF, indeed. I thought you were crazy at first, but I got the same result. WPF baffles me sometimes also. Hopefully, there is some sane reason for this.Buchbinder
A
17

It's because the Transparent brush allows an area to be hittable and thus receive and respond to mouse clicks, whereas the default null brush doesn't. In other words, without any brush defined, the region becomes "hollow" and clicks pass through; with a brush defined (even a transparent one), they are "solid" and clicks can be received.

See this helpful article on WPF brushes for more info.

Acetous answered 16/5, 2009 at 3:45 Comment(4)
I retract my previous WTF statement. That makes perfect sense. +1Buchbinder
That's really good to know, actually. And it actually makes sense why it does that. ThanksRibera
No problem! Glad to be of help.Acetous
Just learning about the canvas, but this is a great description. concise and to the point. kudos good sir!Zebrawood

© 2022 - 2024 — McMap. All rights reserved.