Question

I have a brush that is part of a ResourceDictionary that is merged to Application.Resources.

But for some reason it's not resolved at runtime when a style is being applied to one of the controls. However, if I call Application.Current.FindResource("BrushName") from the Immediate Window at the time when exception is thrown, the resource is found.

Am I missing something? Isn't WPF supposed to try to look for the resource in the app's resources?

UPDATE The application is quite big, so I can't post all actual code but here's the way the resources are merged and used:

Brushes.xaml

<ResourceDictionary ...>
  <SolidColorBrush x:Key="BrushName" Color="#12345678" />
</ResourceDictionary>

SomeStyles.xaml

<ResourceDictionary ...>
  <Style x:Key="SomeStyle">
    <Setter Property="SomeProperty" Value="{StaticResource BrushName}" />
  </Style>
</ResourceDictionary>

App.xaml

<Application ...>
  <Application.Resources>

    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Brushes.xaml" />
        <ResourceDictionary Source="SomeStyles.xaml" />
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>


  </Application.Resources>
</Application ...>

And then some control might use the style using the resource like this:

...
Style={StaticResource SomeStyle}
...

UPDATE

It seems to happen to menus and controls that are created in code. Can it be related to those controls and menus not being parts of any window's visual tree?

Was it helpful?

Solution

Your SomeStyle.xaml dictionary needs to reference Brushes.xaml dictionary directly, like so:

<ResourceDictionary ...>
  <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="Brushes.xaml" />
  </ResourceDictionary.MergedDictionaries>
  <Style x:Key="SomeStyle">
    <Setter Property="SomeProperty" Value="{StaticResource BrushName}" />
  </Style>
</ResourceDictionary>

StaticResources only search up the tree of the current dictionary, so you need to pass in any resources that it needs to reference.

OTHER TIPS

Are you using DynamicResource in the XAML mark up extension?

Your xaml should be {DynamicResource brushName} not {StaticResource brushName}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top