WPF:如何使用透明画布和可单击的子画面进行叠加控制

时间:2022-07-03 15:53:01

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

以下是我尝试实现此目的的方法......首先,我在将要放置叠加层的窗口中使用PreviewMouseDown \ Up \ Move事件。我希望这些事件“通过”我的自定义控件的透明部分,但停止在不透明(例如在我的按钮)。其次,这是我的控件的xaml(root UserControl节点保持不变):

<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.

但是,如果我将Canvas的IsHitTestVisible设置为false,则整个控件包括按钮将变为“unhittable”。如果将其设置为true,则所有隧道事件将停止在自定义控件上,并且按钮将变为不可点击。

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

实现这种行为的正确方法是什么?是否可以在没有子类化画布(或任何其他面板)的情况下这样做?

1 个解决方案

#1


19  

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

您应该将Canvas的背景设置为null(或者只是没有背景,默认为null)。透明对鼠标点击是“可见的”。

#1


19  

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

您应该将Canvas的背景设置为null(或者只是没有背景,默认为null)。透明对鼠标点击是“可见的”。