Search code examples
c#wpfxamluser-controlswpf-controls

Force transparent background on custom UserControl


I want to create a new UserControl and reroute the Background property to use it elsewhere than in the UserControl.Background property (like it is done on the checkbox for example).

Here is a simple custom usercontrol:

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:Controls"
         xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing" 
         x:Class="Controls.HexagonalTile"
         mc:Ignorable="d" d:DesignWidth="300" d:DesignHeight="300">
<Grid>
    <ed:RegularPolygon Fill="{Binding ElementName=LayoutRoot, Path=Background}" StrokeThickness="5" Stroke="Black"/>
</Grid>

And I want to use it like this:

<Controls:HexagonalTile HorizontalAlignment="Left" Height="100" Width="100" Background="Aqua" />

But when I do this, the corner of my user control, outside of the hexagone, take the background color too. I want them to stay transparent.

Thank's for your help.


Solution

  • The reason why this is happening is because the default ControlTemplate for a UserControl has a Border with a TemplateBinding to the Background property.

    However, you can re-template the control like this to achieve your goal:

    <UserControl x:Class="WpfApp4.HexagonalTile"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing">
        <UserControl.Template>
            <ControlTemplate TargetType="{x:Type UserControl}">
                <Grid>
                    <ContentPresenter />
                </Grid>
            </ControlTemplate>
        </UserControl.Template>
        <Grid>
            <ed:RegularPolygon
                Fill="{Binding Background, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
                Stroke="Black"
                StrokeThickness="5" />
        </Grid>
    </UserControl>
    

    I hope this helps!