Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight 4 - use StaticResource from one ResourceDictionary in another

If I have these dictionaries:

dict1.xaml: <Color x:Key="Color1">Red</Color>

dict2.xaml: <SolidColorBrush x:Key="Brush1" Color={StaticResource Color1} />

This works:

App.xaml:

<MergedDictionaries>
  <ResourceDictionary Source="dict1.xaml"/>
<MergedDictionaries>

SomePage.xaml:

<UserControl.Resources>
  <MergedDictionaries>
    <ResourceDictionary Source="dict2.xaml"/>
  </MergedDictionaries>
</UserControl.Resources>

This does not:

App.xaml merging both at application level.

I get an error about Color1 not being found.

Why is this ? / Is there a way around it? I know this example is simplistic, but a real one would be too long. Basically I'm just trying to organize my styles and templates in different files:

  • One for colors
  • One for implicit styles
  • Many for explicit styles

edit: curiously, if I do this in code on Application_Startup, before setting the RootVisual property, I don't get the error... I'm just perplexed as to why!

like image 922
Kir Avatar asked Apr 22 '11 12:04

Kir


1 Answers

Unfortunately you've run into an annoying limitation in the Silverlight resources system which I can only imagine is some optimization issue. There seems to be some asynchronous behaviour here where each dictionary in MergedDictionaries are loaded in parallel, hence when "dict2.xaml" is loading you cannot rely on content of "dict1.xaml" being present.

The simplest solution is to include the merging of Dict1 in Dict2:-

App.xaml:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="dict2.xaml" />
<ResourceDictionary.MergedDictionaries>

Dict2.xaml:

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="dict1.xaml" />
    </ResourceDictionary.MergedDictionaries>
    .... <!-- dict2 resource -->
</ResourceDictionary>
like image 72
AnthonyWJones Avatar answered Nov 15 '22 10:11

AnthonyWJones