WPF BasedOn造型

时间:2011-03-11 15:46:32

标签: c# .net wpf styles

嘿我正在尝试在WPF中设置按钮样式。我有一个基本风格:

    <Style x:Key="buttonStyle" TargetType="{x:Type ButtonBase}">
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate x:Name="ButtonBaseControlTemplate" TargetType="{x:Type ButtonBase}">
                <Grid SnapsToDevicePixels="True">
                    <Border x:Name="Bd" Background="#9BC4E2" BorderBrush="Black"
                            BorderThickness="3,3,3,3" CornerRadius="7,7,7,7" Padding="5,5,5,5">
                        <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" x:Name="Content"
                                      ContentSource="Content"
                                      RecognizesAccessKey="True" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                </Grid>
             <-- Removed triggers here -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

但是我也需要使用它来切换按钮,只是为了改变IsChecked背景颜色。但是当我这样做时,我无法访问边框来设置背景:

<Style TargetType="{x:Type Button}" BasedOn="{StaticResource buttonStyle}">
</Style>

<Style TargetType="{x:Type ToggleButton}" BasedOn="{StaticResource buttonStyle}">
    <Style.Triggers>
        <Trigger Property="IsChecked" Value="True">
            <Setter Property="Background"  Value="White"/> <-- Need to specify target name of the border here somehow -->
        </Trigger>
    </Style.Triggers>
</Style>

有什么建议吗? TA

1 个答案:

答案 0 :(得分:9)

这几乎是为

设计的TemplateBinding

http://devlicio.us/blogs/christopher_bennage/archive/2008/07/04/templatebinding-a-bridge-between-styles-and-templates.aspx

Border.Background属性更改为

Background="{TemplateBinding Background}"

并将此Setter添加到buttonStyle Style

<Setter Property="Background" Value="#9BC4E2" />

然后你可以声明你的ToggleButton是这样的

<ToggleButton Content="ToggleButton" Background="Green" />