Suppose I have a Window displaying a UserControl. The UserControl contains a TextBox which needs to reference a named style defined in Window.Resources:
<Window.Resources>
<Style TargetType="TextBlock" x:Key="myStyle">
<Setter Property="FontSize" Value="20" />
</Style>
</Window.Resources>
If I do:
<TextBlock Style="{StaticResource myStyle}">Hello</TextBlock>
an XamlParseException exception (‘Provide value on ‘System.Windows.StaticResourceExtension’ threw an exception.’) will be thrown when the application is run.
IF I change the reference to a DynamicResource, everything works fine:
<TextBlock Style="{DynamicResource myStyle}">Hello</TextBlock>
Does the StaticResource reference fail because the UserControl’s XAML is lexically parsed before the Window that contains it? In other words, as far as the XAML parser is concerned, is Windows.Resources defined after UserControl?
Thanks!
Ben
Yes, that’s correct – the XAML parser is extremely limited in what it can find with the StaticResource markup extension. It’s not so much about order though – each XAML file is pretty much its own scope and cannot see other resources if they are in different files. As you point out, you can use DynamicResource instead. If you want the benefits of StaticResource (notably design-time support), you can also merge dictionaries (http://msdn.microsoft.com/en-us/library/system.windows.resourcedictionary.mergeddictionaries.aspx) in the resource dictionary of the user control to clue the XAML parser in to additional resource “scopes” that it should consider.
I think merge dictionaries may not work in this particular case though, because I suspect if you merge a parent scope into a child resource dictionary, you may get a duplicate definition error (I haven’t tested it for this specific case though, maybe XAML overrides cleanly).