As I stated earlier, the concept of resources is very
similar to the concept of CSS. The benefits are same. This means you can
easily spread a look across controls, pages or your application. Also by using
resources you can have smaller codes and easily change or modify your look
without changing each and every element many times.
There are two kinds of resources in Windows Presentation
Foundation: Global and Local. Syntax is the same for both kinds, but Global
resources can be declared for whole page and all its controls. However, Local
resources can be declared for a special element.
Another thing that is worth mentioning is that every XAML
element has a set of resources. You must declare a resource before using it,
otherwise compiler cannot understand it. So you must put control resources
before setting the attribute that will use them.
You need to have a reference to the XAML namespace since
some tags to declare resources are in the XAML namespace. So in addition to
default Windows Presentation Foundation, you must have a reference to XAML
namespace (I suppose it is "x:" in my samples). In order to declare
a resource, you must use a key attribute for each resource that is an
identifier that helps you to refer to the resource via other elements. This key
attribute is in XAML namespace. Other attributes are the attributes you use
for your elements to declare your desired look for them.
Listing 5 and its output, Figure 2, show a Global resource.
Listing 5
<Window x:Class="ResourcesInXAML.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Resources In XAML" Height="150" Width="300"
>
<Window.Resources>
<SolidColorBrush x:Key="myBrush" Color="Coral" />
</Window.Resources>
<StackPanel Margin="30">
<Button Background="{StaticResource myBrush}"
Width="200" Height="40">
ASP Alliance
</Button>
</StackPanel>
</Window>
Figure 2
