Search code examples
wpfresourcescode-behind

Resolving resources in C#


In XAML, {StaticResource somename} will fall through from control resources to window resources, and finally application resources. In code behind for the same form, Resources["somename"] appears only to operate on window resources.

I found that in a window's code-behind, in order to resolve a resource that is defined at the application level it is necessary to explicitly refer to App.Current.Resources.

Am I using something incorrectly, or is this expected behaviour?


Solution

  • I'd recommend the Resources Overview.

    When you use the StaticResource markup extension in XAML, it will walk up the logical tree, searching for the "somename" resource. You can do the same thing in code using the FrameworkElement.FindResource (or TryFindResource) method:

            myButton.Background = (Brush)this.FindResource("RainbowBrush");
    

    When you use someFrameworkElement.Resources["somename"], you are directly accessing that framework element's resource dictionary, which is no different than accessing a regular dictionary or hashtable object -- it doesn't have any smarts to traverse up the logical tree.