强制自定义UserControl使用透明背景

3
我希望创建一个新的用户控件,并将Background属性重定向到其他位置使用(例如,像复选框一样)。
下面是一个简单的自定义用户控件:
<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>

我希望能这样使用它:

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

但是当我这样做时,我的用户控件的角落,在六边形外面,也会带有背景颜色。我希望它们保持透明。谢谢您的帮助。

LayoutRoot 元素定义在哪里? - Pavel Anikhouski
1个回答

3
这种情况发生的原因是因为 UserControl 的默认ControlTemplate具有一个Border,其中包含一个对 Background 属性的TemplateBinding

不过,您可以像这样重新制作控件模板以实现您的目标:
<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>

我希望这有所帮助!

谢谢,这正是我所期望的。但是为什么我应该替换填充绑定?是因为“LayoutRoot”在默认模板中定义,而由于我们重新定义了默认模板,所以它不再存在吗? - Corabox
是的。您不能总是依赖其他人定义的控件名称,因为它们可能会更改。我喜欢对我的绑定非常具体化。在这种情况下,我想要绑定到“UserControl”的“Background”属性。 - Keithernet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接