Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF BasedOn Styling

Tags:

c#

.net

styles

wpf

Hey I'm trying to style buttons in WPF. I have a base style:

    <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>

But I need to use this for toggle buttons too, just to change the IsChecked background colour. But I can't access the border to set the background when I try like this:

<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>

Any suggestions? ta

like image 408
Andrew Critchley Avatar asked Feb 10 '26 15:02

Andrew Critchley


1 Answers

This is pretty much what TemplateBinding is designed for

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

Change the Border.Background property to be

Background="{TemplateBinding Background}"

and add this Setter to your buttonStyle Style

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

Then you can declare your ToggleButtons like this

<ToggleButton Content="ToggleButton" Background="Green" />
like image 82
kenwarner Avatar answered Feb 12 '26 14:02

kenwarner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!