1

这是我的应用程序资源中的 XAML,它将应用程序中的所有 Button 控件全局更改为我想要的外观和行为:

<Style TargetType="{x:Type Button}" x:Key="MyButtonStyle">
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="OverridesDefaultStyle" Value="true"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border x:Name="Border" CornerRadius="0" BorderThickness="0" 
                            Background="CornflowerBlue" BorderBrush="CornflowerBlue">
                    <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" />
                </Border>
                <ControlTemplate.Triggers>
                    <!-- a bunch o' triggers here -->
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

在我的应用程序的一个用户控件上,我想更改此按钮的一些属性。这是我现在在 UserControl.Resources 部分中使用的一些 XAML 来执行此操作:

<Style x:Key="SpecialButton" TargetType="Button" BasedOn="{StaticResource MyButtonStyle}">
    <Setter Property="Width" Value="20" />
    <Setter Property="Visibility" Value="Collapsed" />
    <Setter Property="Content" Value=">" />
    <Setter Property="Border" Value="#eeeeee" />
    <Setter Property="Border.Background" Value="#eeeeee" />
</Style>

我的 UserControl 上分配 SpecialButton 样式的 Button 控件具有正确的宽度、可见性和内容,但最后两次尝试不起作用。我将如何从这种特殊按钮样式的应用程序资源中更改名称为“边框”的边框的背景颜色?

4

1 回答 1

2

您可以做的是使用TemplateBinding在基本样式中设置控件的背景属性。同样在基本样式中,将背景颜色设置为默认的“CornflowerBlue”。

<Setter Property="Background" Value="CornflowerBlue" />
<Setter Property="Template">
    <Setter.Value>    
        <ControlTemplate TargetType="{x:Type Button}">
            <Border x:Name="Border" Background="{TemplateBinding Background}"

现在您可以覆盖派生样式中的背景:

<Style x:Key="SpecialButton" TargetType="Button" BasedOn="{StaticResource MyButtonStyle}">
    <Setter Property="Background" Value="#eeeeee" />

(请注意,如果您想使用未在 Button 控件上定义的其他属性 - 或者说您想使用多种背景颜色 - 那么您必须创建自己的控件来继承Button,并公开新属性作为依赖属性。)

于 2012-12-13T20:25:33.567 回答