Here is a sample of using a ControlTemplate to customize a button.
The result is a circular button with a radial brush that, when clicked, animates the origin of the brush from the center by a small offset - and then back.
I put it in a page so you can copy this snippet to a text file and open with Internet Explorer.
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1" Height="300" Width="300">
<Page.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Ellipse Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<Ellipse.Fill>
<RadialGradientBrush x:Name="radialBrush" SpreadMethod="Pad">
<GradientStop Offset="1" Color="Red"></GradientStop>
<GradientStop Offset="0" Color="White"></GradientStop>
</RadialGradientBrush>
</Ellipse.Fill>
</Ellipse>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="ButtonBase.Click">
<BeginStoryboard>
<Storyboard
TargetName="radialBrush"
TargetProperty="GradientOrigin">
<PointAnimation
From="0.5,0.5"
To="0.4,0.4"
Duration="0:0:1"
AutoReverse="true">
</PointAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<Button Height="300" Width="300"/>
</Page>
Here are the highlights:
- The page contains one button and a style (in Page.Resources).
- The style applies to Button controls without a key – and therefore applies by default to all buttons in the Page.
- The style contains only one Setter which is the one that sets the Template property of the Button.
- The value of the Setter is a ControlTemplate that contains two parts: content – an Ellipse, and one trigger – for the animation.
- The Ellipse uses the TemplateBinding markup extension to grab the actual Width and Height of the button.
- The Ellipse’s Fill property is a RadialGradientBrush called radialBrush that is centered at (0.5, 0.5). This is interpreted as the center of the Ellipse’s bounding rectangle.
- radialBrush goes from White at the center (Offset 0) to Red at the edge (Offset 1).
- SpreadMethod is set to Pad so that when the center of the brush is moved away from the center of the Ellipse, the area of the Ellipse beyond Offset 1 is colored Red.
- The Trigger of the ControlTemplate is an EventTrigger, triggered by a click on the Button (ButtonBase.Click)
- When the event is triggered, a PointAnimation is executed.
- The PointAnimation moves the GradientOrigin from (0.5, 0.5) (center) to (0.4, 0.4) over a 1 second interval – and then reverses the operation.