Silverlight and WPF - How to find StaticResource from code behind

By Robbe Morris

Quick tip for finding a StaticResource in code behind for setting the .Style property of a XAML control dynamically.

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;

public static class StyleController
{
     public static FrameworkElement ApplicationRootElement = null;
     public static ResourceDictionary ResourceDictionary = null;


     public static void Initialize(FrameworkElement applicationRootElement, ResourceDictionary resourceDictionary)
     {
        ApplicationRootElement = applicationRootElement;
        ResourceDictionary = resourceDictionary;
      }


      public static object FindResource(string name)
      {
          if (ResourceDictionary == null)
               throw new Exception("ResourceDictionary has not been set.");

          if (ApplicationRootElement == null)
               throw new Exception("ApplicationRootElement has not been set.");


          if (ResourceDictionary.Contains(name)) return ResourceDictionary[name];

          return ApplicationRootElement.FindResource(name);
      }

      internal static object FindResource(this FrameworkElement root, string name)
      {
          if (root != null && root.Resources.Contains(name)) return root.Resources[name];

          try
         {
            return root.FindName(name);
          }
         catch { }
         return null;
      }
}

// Initialize the controller in your main UserControl/Window when your app starts up

StyleController.Initialize((FrameworkElement)this, App.Current.Resources);

// Use syntax

textBlock.Style = (Style)StyleController.FindResource("TextBlockLabel");

Related FAQs

Quick tip for retrieving querystring variables in Silverlight code behind.
Silverlight and WPF - How to find StaticResource from code behind  (11126 Views)