title: Setting a static Style resource from c# Code in WPF
body: <p>My style <code>test</code> is defined as a resource in a <code>ResourceDictionary</code> in UserControl, like this:</p>
  
  <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
  
  &lt;Style x:Key="test" TargetType="ContentControl"&gt;
      &lt;!--&lt;Setter Property="Visibility" Value="Visible" /&gt;--&gt;
      &lt;Setter Property="Template"&gt;
          &lt;Setter.Value&gt;
              &lt;ControlTemplate TargetType="ContentControl"&gt;
                  &lt;TextBlock Text="TESTTTT" Foreground="Black"/&gt;
              &lt;/ControlTemplate&gt;
            &lt;/Setter.Value&gt;
         &lt;/Setter&gt;
     &lt;/Style&gt;
  &lt;/ResourceDictionary&gt;
  </code></pre>
  
  <p>UserControl:</p>
  
  <pre><code>&lt;ResourceDictionary&gt;
      &lt;ResourceDictionary.MergedDictionaries&gt;
          &lt;ResourceDictionary Source="Dictionary1.xaml" /&gt;
      &lt;/ResourceDictionary.MergedDictionaries&gt;
  &lt;/ResourceDictionary&gt;
  </code></pre>
  
  <p>In the code behind file of this UserControl I'am trying to get that Style and apply it to a content control, which is defined in the same UserControl.</p>
  
  <p>Here is my UserControl.xaml:</p>
  
  <pre><code>&lt;UserControl x:Class="WpfApplication2.MainWindow"
               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
               Height="350" Width="525" Loaded="Window_Loaded"&gt;
      &lt;UserControl.Resources&gt;
          &lt;ResourceDictionary&gt;
              &lt;ResourceDictionary.MergedDictionaries&gt;
                  &lt;ResourceDictionary Source="Dictionary1.xaml" /&gt;
              &lt;/ResourceDictionary.MergedDictionaries&gt;
          &lt;/ResourceDictionary&gt;
      &lt;/UserControl.Resources&gt;
  
      &lt;Grid&gt;
          &lt;ContentControl Name="testControl" /&gt;
      &lt;/Grid&gt;
  &lt;/UserControl&gt;
  </code></pre>
  
  <p>and in code-behind in the Loaded event handler I wrote:</p>
  
  <pre><code>UserControl m = sender as UserControl;
  Style s = m.Resources["test"] as Style; 
  // I also tried to reference style in App resources, but it didn't make any difference 
  //(Style)Application.Current.FindResource("test");
  m.testControl = new ContentControl();
  m.testControl.Style = s;
  m.testControl.ApplyTemplate();
  </code></pre>
  
  <p>In debugging mode I saw the found style. Template Controls can also be found by searching for the using their keys/Names. But they wont be shown. It just show an empty user control without any controls from my template defined in the style.</p>
  
  <p>I hope you can help me and thanks in advance!</p>