Alex Alex - 1 year ago 72 Question

How do I access a resource(style) through code?

I have a Resource Dictionary containing all my custom styles for the programs controls.
The Dictionary is mergerd with the application's resources as displayed below:

<ResourceDictionary x:Key="Controls">
<ResourceDictionary Source="Controls.xaml" />

I can easily access the different styles through xaml:

<Button Style="{StaticResource Button}" />

But whenever I try assigning controls with this style through code, it fails.

I've tried:

Button.Style = Application.Current.Resources("Button")

Button.Style = CType(Application.Current.Resources("Button"), Style)

And different approaches similar to the ones above.
During testing some of the different ways to get the styles, I was faced with "Resource not found" but when using the above ones the program seemed to find the style.
I could successfully run the program - but without any visual proof that the style was indeed applied.

How do I properly assign a control a style found in a Resource Dictionary?

Answer Source

For any descendants: here is how I succeded to apply a style from a resource to a dynamically created control through code. (Given that you have a Resource Dictionary containing the style)

First step: Include the Resource Dictionary

To make a Resource Dictionary easily accessible from code, add it through code.


  Dim myResourceDictionary As New ResourceDictionary
  myResourceDictionary .Source = New _


   var myResourceDictionary = new ResourceDictionary
           Source = new Uri("/YourApplication;component/YourDictionary.xaml", UriKind.RelativeOrAbsolute)

Replace "YourApplication" with your solution name, and "YourDictionary" with your Resource Dictionary file.

Second step: Assign the Style

To make use of the newly imported Resource Dictionary, simply assign a control a style;


  Dim myButton As New Button
  Dim myButtonStyle As Style = myResourceDictionary("YourStyleKey")
  myButton.Style = myButtonStyle


  var myButtonStyle= myResourceDictionary["YourStyleKey"] as Style;
  var myButton = new Button { Style = myButtonStyle };

Special thanks to user Stefan Denchev for giving me an article covering this. As C# isn't my strong side, please edit this if I've made any mistake.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download