12
votes

I want to use StaticResource in the root element of a xaml document. But MSDN says:

Static resource references from within a resource dictionary must reference a resource that has already been defined lexically before the resource reference. Forward references cannot be resolved by a static resource reference.

And this:

The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.

Should I define my resource in the application or create it from code?

2
Actually I'm open to anything...naeron84
Do you really need to access it from the root element? Would it not be sufficient to reference it from the top level child element?TabbyCool
The root element is a window and what I'd like to bind to is the Left property. I have forgotten to mention that the StaticResource is a Converter (implements IValueConverter).naeron84

2 Answers

17
votes

You can actually set any property as an element as well as an attribute, including ones as simple as Window.Left.

This means you can set the value of Left after you declare your resources.

<Window.Resources>
    <app:LeftConverter
        x:Key="LeftConverter" />
</Window.Resources>

<Window.Left>
    <Binding
        Path="UnconvertedLeft"
        Converter="{StaticResource LeftConverter}" />
</Window.Left>
3
votes

If you really need to access a ResourceDictionary from the root element, you may be able to reference it as a DynamicResource rather than a StaticResource - I'm not sure if it will work, but it could be worth a try.