WPF 用户控件作为多边形

WPF UserControl as Polygon

我是这个 WPF 世界的新手,我对经典 Windows 桌面应用程序有一些经验。 我正在尝试创建一个自定义的 UserControl 多边形形状。 我尝试创建一个路径数据,然后将 UserControl 不透明度 属性 设置为“0”,但它使整个 UserControl 变得透明。

例如,我在用户控件中构建了这个多边形

<UserControl x:Class="WindowsFormsApp2.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
Width="640" Height="480" Opacity="100">

<Grid x:Name="LayoutRoot">
    <Path Data="M-70.616296,46.859802 L7.3270039,-1.2587545 174.31959,52.958763 168.71134,98.185567 z" Fill="#FF2121D6" HorizontalAlignment="Left" Height="100" Margin="138,114,0,0" Stretch="Fill" Stroke="Black" Opacity ="100" VerticalAlignment="Top" Width="246"/>
</Grid>

如您所见,用户控件是 640x480,因此当我向 UserControl_MouseLeftButtonDown 事件添加代码时,如果在 640x480 内的任意位置单击它会触发,而我只想在多边形内单击时触发。

我一直在谷歌搜索解决方案,但我找不到任何解决方案,也许我想要的是不可能的?

您可以将 UserControl 模板化为看起来像多边形:

<UserControl x:Class="WpfApp1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <Path Data="M-70.616296,46.859802 L7.3270039,-1.2587545 174.31959,52.958763 168.71134,98.185567 z" 
                  Fill="#FF2121D6" HorizontalAlignment="Left" Height="100" Margin="138,114,0,0" 
                  Stretch="Fill" Stroke="Black" Opacity ="100" VerticalAlignment="Top" Width="246"/>
        </ControlTemplate>
    </UserControl.Template>
</UserControl>

或者您可以去掉 UserControl 并直接使用 Path 元素。它还有一个您可以处理的 MouseLeftButtonDown 事件。