Appendix B: Introduction to XAML

415

will change automatically. Listing B-3 defines a brush resource of a specific color and shows how to reference that brush from multiple buttons using a markup extension.

Listing B-3 Markup extension for using resources

<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525">

<Window.Resources>

<SolidColorBrush x:Key="ButtonBrush" Color="Yellow" /> </Window.Resources>

<StackPanel>

<Button Background="{StaticResource ResourceKey=ButtonBrush}" Content="Button One" />

<Button Background="{StaticResource ResourceKey=ButtonBrush}" Content="Button Two" />

</StackPanel>

</Window>

The Window.Resources element in Listing B-3 is a property element of Window. It contains a SolidColorBrush with Color set to Yellow. Everything in WPF and Silverlight is drawn with brushes, which define colors, gradients, images, media, or patterns. In this case, we’ll keep it simple with a single color, which is what SolidColorBrush is good for. The point here is not what a brush is, but the fact that the brush is a resource that will help demonstrate how to use a markup extension to access that resource. It’s important to assign a key to every resource because that key is what resource markup extensions use to identify the resource.

You can see the markup extension assigned to the Background attributes of the Button elements in Listing B-3. Markup extensions are surrounded by curly braces. Within the curly braces are the extension type and attributes associated with the extension. In Listing B-3, the extension type is StaticResource, which allows you to refer to a resource. The ResourceKey attribute of the StaticResource extension specifies the particular resource to use. The value, ButtonBrush, matches the key of the SolidColorBrush resource. So, the value of the BackGround attribute of the Button elements is a StaticResource for a SolidColorBrush that has its color set to Yellow. This effectively means that the Buttons will have Yellow backgrounds.

To see the value of using resources, consider the situation you would be in if you set the BackGround attribute of each button directly to Yellow instead of using the

Page 438
Image 438
Microsoft 9GD00001 manual 415, Listing B-3 Markup extension for using resources