According to MSDN, Silverlight static resources lookup mechanism should:
The lookup behavior for a StaticResource starts with the object where the actual usage is applied, and its own Resources property. (…) The lookup sequence then checks the next object tree parent. (…) Otherwise, the lookup behavior advances to the next parent level towards the object tree root, and so on.
That’s pretty straightforward, as it narrows down to simply traversing objects graph until requested resource key is found. One might assume, this would therefore work:
<UserControl x:Class="ResourcesExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ResourcesExample="clr-namespace:ResourcesExample"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
<SolidColorBrush Color="Green" x:Key="GreenBrush"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<ResourcesExample:Tester />
</Grid>
</UserControl>
<UserControl x:Class="ResourcesExample.Tester"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot">
<TextBlock Text="Show green!" Foreground="{StaticResource GreenBrush}"/>
</Grid>
</UserControl>
Well it doesn’t. What I get instead is XamlParseException : Cannot find a Resource with the Name/Key GreenBrush.
Am I missing something obvious here or documentation is incorrect?
That’s because before inserting the child UserControl in the mother UserControl, it has to be fully instantiated, and since it doesn’t know its parent just yet, it doesn’t know about the SolidColorBrush.
If you put the SolidColorBrush in your Appl.xaml’s Resources section, it will work: App.xaml is loaded at application startup, and any resource you put in there will be globally available.
That said, you could also expose a InnerTextForeground Dependency Property in the child UserControl, and set it to your local SolidColorBrush resource in the parent UserControl.
It’s not very difficult but let me know if you have trouble doing so.