tags:

views:

27

answers:

1

I created a button. My basic requirements are rounded thicker border, with more than one color (i.e. for Buy/Sell buttons)

I was hoping that i could create the template once, and than just override the border brush like this:

<Style x:Key="BorderButton">
  <Setter Property="Control.Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Border BorderThickness="2" 
         BorderBrush="Red" 
         CornerRadius="3" 
         Background="{x:Null}">
           <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Border>
      </ControlTemplate>
     </Setter.Value>            
    </Setter>
  </Style>

  <Style x:Key="GreenBorderButton" BasedOn="{StaticResource BorderButton}" TargetType="{x:Type Button}">
    <Setter Property="BorderBrush" Value="Green" />
  </Style>

but they both produce the same style. Do i need to write out the whole template every time? seems like unnecessary code repetition (especially if 3-4 colors are desired). Hoping there is some way to inherit a template.

+1  A: 

Your code is very close to working; the issue is that GreenBorderButton is applying the BorderBrush to the button itself, not the Border in the overridden Template.

To fix this, simply change the Border's BorderBrush to use the parent Button's BorderBrush. You can do this using a TemplateBinding like so:

<Style x:Key="BorderButton">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border x:Name="border"
                        BorderThickness="2" 
                        BorderBrush="{TemplateBinding Property=BorderBrush}"
                        CornerRadius="3" 
                        Background="{x:Null}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Then, you can either use the same overridden styles like you have, or you could simply do:

<Button Style="{StaticResource BorderButton}" BorderBrush="Blue" Content="Blue" />
Jeremy
that's great thanks. is it possible to apply TemplateBinding to other properties, such as GradientStop ? for example, to create a Gradient button template, but manipulate which 2 colors are applied to it??
Sonic Soul