Blog
XAML Hierarchy of Resources
By Ken Getz | November 13, 2012
In XAML, every element maintains its own resources collection, and also has access to the resources collection of its parent elements. As with many other areas of programming, each element uses resources from the most local source. In other words, if you refer to a resource within a given element, it will first look at its own resources, then at its parent's resources, then its parent's parent's resources, and so on.
Where does the search end? At the topmost level, each application can place references to resources at the application level, in the App.xaml file. If you refer to a resource in an element and the XAML parser can't find the resource in the element or any of its parents, it looks as a last resort in this file-if it can't find a match there, it gives up and raises an error.
Take a look at the ResourceHierarchy page. In this example, shown below, the markup defines two separate resources: BackgroundBrush is defined at the Page level, and StackPanelBackgroundBrush is defined at the StackPanel level.
The markup for the page resources looks like the following:
<Page.Resources>
<LinearGradientBrush x:Key="BackgroundBrush">
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0"
Color="White" />
<GradientStop Offset="0.25"
Color="Yellow" />
<GradientStop Offset="0.5"
Color="Orange" />
<GradientStop Offset="1"
Color="Blue" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Page.Resources>
The markup for the content of the page looks like the following:
<StackPanel>
<StackPanel.Resources>
<SolidColorBrush x:Key="LocalBackgroundBrush"
Color="Pink" />
</StackPanel.Resources>
<Button Content="First Button"
HorizontalAlignment="Stretch"
Margin="5"
Background=
"{StaticResource LocalBackgroundBrush}" />
<Button Content="Second Button"
HorizontalAlignment="Stretch"
Margin="5"
Background=
"{StaticResource BackgroundBrush}" />
</StackPanel>
If you investigate the markup carefully, you'll see that each button uses a different resource to supply its Background property. The first button uses LocalBackgroundBrush (a solid Pink brush), defined by its parent container.
The second button uses BackgroundBrush (a linear gradient with several gradient stops) defined in the page. The XAML parser resolved the background for the second button by looking in the Button, then the StackPanel, and then the page resources, where it found a match.