May 07

StaticResource extension and lookup behavior

Posted in Silverlight      Comments Off on StaticResource extension and lookup behavior

While I was investigating Silverlight for my next PT book, I’ve found this official document from MS that describes the lookup algorithm for the StaticResource extension. According to it, here’s the algorithm used by this extension:

The lookup behavior for a StaticResource is that the markup compile pass for XAML first checks whether the object where the actual usage is applied can hold aFrameworkElement.Resources value. If it can, that ResourceDictionary is checked for an item that has that key. This level of lookup is rarely relevant because you usually do not define and then reference a resource on the same object.

I know that English is not my main language, but after reading, and re-reading it I’m really under the impression that it’s saying that StaticResource will always search the element’s resources where it is applied before going through the ancestors in the logical tree. Now, that means that this should work:

<StackPanel x:Name="panel" Orientation="Vertical" Background="{StaticResource brush}">
        <SolidColorBrush x:Key="brush" Color="Red" />
    <Button Content="Hi"
            Background="{StaticResource brush}"/>

If you look at it, you’ll notice that the StackPanel is trying to use a resource defined in its Resources collection. Unfortunately, it really doesn’t work. Not even in WPF! From a parsing point of view, that’s not that unexpected because the parser hasn’t yet reached the resource definitions when it encounters the StaticResource (I believe that is why you can only reference previously declared resources when creating a new resource).

If I’m not wrong in my analysis, can someone at MS (please!) update the docs?