15

I want to make a custom control which will be used as an overlay. The control should contain a couple of child controls which should be drawn and should be clickable as usual. But everything else in the control should be transparent and "clickable-through".

Here is how I try to achieve this... First, I'm using PreviewMouseDown\Up\Move events in the window where the overlay is going to be placed. I want these events to "go through" transparent part of my custom control, but stop at not-transparent (for example at my button). Second, here is the xaml for my control (root UserControl node was left untouched):

<Canvas Background="transparent" IsHitTestVisible="true">
     <Button Canvas.Left="384" Canvas.Top="34" Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" IsHitTestVisible="True" />
     <TextBlock Canvas.Left="27" Canvas.Top="105" Height="36" Name="textBlock1" Text="TextBlock" Width="432" FontSize="24" IsHitTestVisible="False" Foreground="Red" FontWeight="Bold" />
</Canvas>

However if I set Canvas' IsHitTestVisible to false, the whole control including button becomes "unhittable". If set the it to true my all the tunneling events stop at custom control and button becomes unclickable.

What is the right way to achieve this kind of behavior? Is it possible to do so without subclassing canvas (or any other panel)?

Pavel Murygin
  • 2,242
  • 2
  • 18
  • 26

1 Answers1

20

You should set the background of the Canvas to null (or just no background, null is default). Transparent is "visible" to the mouse clicks.

Vlad
  • 35,022
  • 6
  • 77
  • 199
  • @Vlad, hi, nice to see you again! Does it work so that when the background is null means button inside can not be clicked, however, when the background is transparent means button can be clicked? /// By the way, thanks a lot for your previous help. I mean the TextHighlightBlock control (yellow/orange highlight color). You helped me to make it fast. Many guys in my company told me that the work had been done nicely, and this conltrol was an important part of it. – Andrey K. Oct 11 '17 at 14:09
  • @AndreyK.: Well, there's no hard-and-fast rule. A panel with background (white or red or transparent, doesn't matter) takes part in the hit test. So the mouse events _can_ be delivered to such a panel. A panel with `null` (that is, no) background don't take part in hit test process. For normal events, hit test goes from inner to outer controls (so the click on the button works even if canvas' background is set to transparent), but for preview events it's vice versa, that's the reason the OP had a problem. – Vlad Oct 11 '17 at 15:09