tags:

views:

30

answers:

1

Hello,

we just got started with XAML and are still fighting with basic issues: Coming from CSS we'd like to define a generic button style with custom control template and then have a second style inherit everything from the first style using "basedon. This second style should then override properties such e.g. "foreground color" (which works) but also properties of child elements within our custom template such as the "background color" of e.g. an included border element etc. (which doesn't work).

What's the general approach to go about things like this? How far can we go with cascading styles?

Cheers!

A: 

The standard approach to making a customizable control template is to use TemplateBinding in the template to bind to properties of the control, and then to set those properties in the child styles.

For example, this creates a button template with a Border control, and binds the Background of the Border to the Background property of the Button. By setting the Background property of the Button in other styles, it changes the Background property of the Border.

<StackPanel>
    <StackPanel.Resources>
        <Style x:Key="BaseButtonStyle" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}">
                            <ContentPresenter/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="BlueButtonStyle" TargetType="Button"
               BasedOn="{StaticResource BaseButtonStyle}">
            <Setter Property="Background" Value="Blue"/>
        </Style>
        <Style x:Key="RedButtonStyle" TargetType="Button"
               BasedOn="{StaticResource BaseButtonStyle}">
            <Setter Property="Background" Value="Red"/>
        </Style>
    </StackPanel.Resources>
    <Button Style="{StaticResource RedButtonStyle}">Red</Button>
    <Button Style="{StaticResource BlueButtonStyle}">Blue</Button>
</StackPanel>

Many of the properties on Control are intended to be used in control templates, and won't affect other behavior if they are changed. They are BorderBrush, BorderThickness, Background, Padding, HorizontalContentAlignment, and VerticalContentAlignment.

Quartermeister