WPF Simple ControlTemplate Sample

16 ביולי 2009

אין תגובות

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.




  Title="Page1" Height="300" Width="300">


      <Style TargetType="{x:Type Button}">

         <Setter Property="Template">



                  <Ellipse Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">


                        <RadialGradientBrush x:Name="radialBrush" SpreadMethod="Pad">

                           <GradientStop Offset="1" Color="Red"></GradientStop>

                           <GradientStop Offset="0" Color="White"></GradientStop>





                     <EventTrigger RoutedEvent="ButtonBase.Click">




















   <Button Height="300" Width="300"/>


Here are the highlights:

  1. The page contains one button and a style (in Page.Resources).
  2. The style applies to Button controls without a key – and therefore applies by default to all buttons in the Page.
  3. The style contains only one Setter which is the one that sets the Template property of the Button.
  4. The value of the Setter is a ControlTemplate that contains two parts: content – an Ellipse, and one trigger – for the animation.
  5. The Ellipse uses the TemplateBinding markup extension to grab the actual Width and Height of the button.
  6. 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.
  7. radialBrush goes from White at the center (Offset 0) to Red at the edge (Offset 1).
  8. 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.
  9. The Trigger of the ControlTemplate is an EventTrigger, triggered by a click on the Button (ButtonBase.Click)
  10. When the event is triggered, a PointAnimation is executed.
  11. 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.
הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *