wpfxamlblend

WPF UserControl as Polygon


I am very new at this WPF world, i have some experience in the classic Windows Desktop applications. I am trying to create a custom UserControl polygon shaped. I have tryied creating a Path Data and then setting the UserControl Opacity property to "0", but it makes transparent the whole UserControl.

For example, i have build this Polygon inside the user control

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

As you can see the user control is 640x480 so when i add code to the UserControl_MouseLeftButtonDown event, it fires if clicking in ay position inside the 640x480 while i want only to fire when clicking inside the polygon.

I have been googling for a solution but i can't found any solution, ¿maybe what i want it's not possible?


Solution

  • You may template a UserControl to look like a polygon:

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

    Or you may just get rid of the UserControl and use the Path element directly. It also has a MouseLeftButtonDown event that you can handle.