C# ControlTemplate使用控件属性

C# ControlTemplate使用控件属性,c#,wpf,xaml,C#,Wpf,Xaml,ControlTemplate是否可以使用控件中使用该模板的属性 例如,我有一个按钮,鼠标悬停时,它的颜色会变为红色。但是,我还有一个按钮,看起来完全一样,只是它变为白色,而不是红色。是否有可能,无论按钮具有何种背景值,该值都会在控件模板中使用 目前,这是我的ControlTemplate的外观: <ControlTemplate x:Key="CloseButtonTemplate" TargetType="{x:Type Button}"> <Border&

ControlTemplate是否可以使用控件中使用该模板的属性

例如,我有一个按钮,鼠标悬停时,它的颜色会变为红色。但是,我还有一个按钮,看起来完全一样,只是它变为白色,而不是红色。是否有可能,无论按钮具有何种背景值,该值都会在控件模板中使用

目前,这是我的ControlTemplate的外观:

<ControlTemplate x:Key="CloseButtonTemplate" TargetType="{x:Type Button}">
        <Border>
            <Border.Style>
                <Style>
                    <Setter Property="Border.Background" Value="Transparent"/>
                    <Style.Triggers>
                        <Trigger Property="Border.IsMouseOver" Value="True">
                            <Setter Property="Border.Background" Value="#FFE53935" />
                            <Setter Property="Window.Cursor" Value="Hand" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
            <TextBlock Foreground="#FFEEEEEE" HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" FontFamily="Calibri" />
        </Border>
</ControlTemplate>

我要做的是,将Border.Background设置为按钮的背景值。因此,如果我有a,则Border.Background的值为红色。

您可能应该这样做:

<Border x:Name="border" Background="{TemplateBinding Background}">

请参见

是,ControlTemplate可以使用控件中使用该模板的属性。有关绑定,请参见此


这就是我要找的。谢谢
   <Window.Resources>
    <ControlTemplate x:Key="CloseButtonTemplate" TargetType="{x:Type Button}">
        <Border BorderBrush="Black" BorderThickness="1"  Height="{TemplateBinding Height}" Width="{TemplateBinding Width}">
            <Border.Style>
                <Style>
                    <Setter Property="Border.Background" Value="Transparent"/>
                    <Style.Triggers>
                        <Trigger Property="Border.IsMouseOver" Value="True">
                            <Setter Property="Border.Background" Value="{Binding Path=Background,RelativeSource={RelativeSource TemplatedParent}}" />
                            <Setter Property="Window.Cursor" Value="Hand" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
            <TextBlock Foreground="#FFEEEEEE" HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" FontFamily="Calibri" />
        </Border>
    </ControlTemplate>
</Window.Resources>
<UniformGrid>
    <Button Background="Red" Template="{StaticResource CloseButtonTemplate}"  Height="30" Width="200"/>
    <Button Background="Green" Template="{StaticResource CloseButtonTemplate}"  Height="30" Width="200"/>
    <Button Background="Blue" Template="{StaticResource CloseButtonTemplate}"  Height="30" Width="200"/>
</UniformGrid>