开发者

WPF resource merged to Application.Resources but not resolved at runtime

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开发者_JS百科.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?


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.


Are you using DynamicResource in the XAML mark up extension?

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜