More on Triggers and Styles and Control Templates - Control Templates
(Page 2 of 5 )
If we take a closer look at our current tic-tac-toe game, we’ll see that the Button objects aren’t quite doing the job for us. What tic-tac-toe board has rounded inset corners (Figure 5-14)?
What we really want here is to be able to keep the behavior of the button—i.e., holding content and firing click events—but we want to take over the look of the

Figure 5-14. Tic-tac-toe boards don't have rounded insets!
button. WPF allows this kind of thing because the intrinsic controls are built to be lookless—i.e., they provide behavior, but the look can be swapped out completely by the client of the control.
Remember how we used data templates to provide the look of a non-visual object? We can do the same to a control using a control template, which is a set of storyboards, triggers, and, most importantly, elements that provide the look of a control.
To fix our buttons’ looks, we’ll build ourselves a control-template resource. Let’s start things off in Example 5-31 with a simple rectangle and worry about showing the actual button content later.
Example 5-31. A minimal control template
<Window.Resources>
<ControlTemplate x:Key="ButtonTemplate">
<Rectangle />
</ControlTemplate>
...
<!-- let's just try one button for now... -->
<Button Template="{StaticResource ButtonTemplate}" ... />
...
</Window.Resources>
Figure 5-15 shows the results of setting a single button’sTemplate property.
Notice that no vestiges of what the button used to look like remain in Figure 5-15. Unfortunately, no vestige of our rectangles can be seen, either. The problem is that, without a fill explicitly set, the rectangle’s fill defaults to transparent, showing the grid’s black background. Let’s set it to our other favorite Halloween color instead:
<ControlTemplate x:Key="ButtonTemplate">
<Rectangle Fill="Orange" />
</ControlTemplate>

Figure 5-15. Replacing the control template with something less visual than we'd like...
Now we’re getting somewhere, as Figure 5-16 shows.

Figure 5-16. Replacing the button’s control template with an orange rectangle (Color Plate 11)
Notice how square the corners are? Also, if you click, you won’t get the depression that normally happens with a button (and I don’t mean “a sad feeling”).
Next: Control Templates and Styles >>
More XML Articles
More By O'Reilly Media
|
This article is excerpted from chapter five of the book Programming Windows Presentation Foundation, written by Chris Sells and Ian Griffiths (O'Reilly; ISBN: 0596101139). Check it out today at your favorite bookstore. Buy this book now.
|
|