WPF: How to make an overlay control with transparent canvas and clickable child

Pavel Murygin picture Pavel Murygin · Oct 21, 2011 · Viewed 18.8k times · Source

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)?

Answer

Vlad picture Vlad · Oct 21, 2011

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