Accessing XAML resources in code

I have a bunch of brushes, colours etc. within the Generic.xaml file inside a ResourceDictionary and I needed to get at the resources from code.

So let’s assume our XAML looks like this

<ResourceDictionary 
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush 
       x:Key="DisabledBackgroundBrush" 
       Color="#FFF0F0F0" />
    <SolidColorBrush 
       x:Key="DisabledForegroundTextBrush" 
       Color="DarkGray" />
</ResourceDictionary>

Now to access these resource from code I’m going to use the following class/code

public static class GenericResources
{
   private static readonly ResourceDictionary genericResourceDictionary;

   static GenericResources()
   {
      var uri = new Uri("/MyAssembly;component/Generic.xaml", UriKind.Relative);
      genericResourceDictionary = (ResourceDictionary)Application.LoadComponent(uri);			
   }

   public static Brush ReferenceBackColor
   {
      get { return (Brush) genericResourceDictionary["DisabledBackgroundBrush"]; }
   }

   public static Brush DisabledForeground
   {
      get { return (Brush)genericResourceDictionary["DisabledForegroundTextBrush"]; }
   }
}

As you can see we create a Uri to the XAML using the format “/<assembly_name>;component/<subfolders>/<xaml_filename>”. Next we get the ResourceDictionary via the LoadComponent method. Now to access the resource dictionary assets via the key’s we simply use the dictionary’s indexer and cast to our expected type.

And that’s all there is to it.