Here’s an interesting omission in Silverlight that I stumbled upon today: Silverlight doesn’t provide you with a way to do a hierarchical resource look-up in code.
You can do it in XAML. Write
<Grid> <Grid.Resources> <Style x:Key="MyStyle> </Style> </Grid.Resources> <DockPanel> <Button> <TextBlock Style="{StaticResource MyStyle}"/> </Button> </DockPanel> </Grid>
and the TextBlock will find the appropriate style in the Grid’s resource dictionary, even though it’s several layers up the hierarchy. And if the resource isn’t found in any of the parent elements, StaticResource will then look in the Application’s Resource Dictionary.
But, whereas WPF provides the TryFindResource method to do the same kind of look-up in code, the best you can do in Silverlight is
element.ResourceDictionary[“MyStyle”]and that returns null if the resource isn’t in the element’s own ResourceDictionary.
No matter. It’s easy to a proper lookup yourself:
public static class FrameworkElementExtensions { public static object TryFindResource(this FrameworkElement element, object resourceKey) { var currentElement = element; while (currentElement != null) { var resource = currentElement.Resources[resourceKey]; if (resource != null) { return resource; } currentElement = currentElement.Parent as FrameworkElement; } return Application.Current.Resources[resourceKey]; } }
With that in place
textBox.TryFindResource("MyStyle");will do what you expect.
Which of course makes me wonder why this was omitted from Silverlight in the first place. Am I missing something?