title: Setting WPF Button Style Programmatically
body: <p>I have the below style:</p>
  
  <pre><code>&lt;Window.Resources&gt;
      &lt;Style x:Key="RoundCorner" TargetType="{x:Type Button}"&gt;
          &lt;Setter Property="HorizontalContentAlignment" Value="Center"/&gt;
          &lt;Setter Property="VerticalContentAlignment" Value="Center"/&gt;
          &lt;Setter Property="Padding" Value="1"/&gt;
          &lt;Setter Property="Template"&gt;
              &lt;Setter.Value&gt;
                  &lt;ControlTemplate TargetType="{x:Type Button}"&gt;
                      &lt;Border CornerRadius="0,0,4,4" BorderBrush="black" 
       BorderThickness="1,0,1,1" &gt;
                          &lt;ContentPresenter HorizontalAlignment="Center"
                              VerticalAlignment="Center"
                              Margin="1"&gt;&lt;/ContentPresenter&gt;
                      &lt;/Border&gt;
                  &lt;/ControlTemplate&gt;
              &lt;/Setter.Value&gt;
          &lt;/Setter&gt;
          &lt;Setter Property="LayoutTransform"&gt;
              &lt;Setter.Value&gt;
                  &lt;RotateTransform CenterX="0.5" CenterY="0.5" Angle="270" /&gt;
              &lt;/Setter.Value&gt;
          &lt;/Setter&gt;
      &lt;/Style&gt;
  &lt;/Window.Resources&gt;
  </code></pre>
  
  <p>I am setting it to a button like this   </p>
  
  <pre><code>&lt;Button x:Name="btn_bfx" ToolTip="BreakFix" Content="BFX" Click="btn_bfx_Click" Height="30" Width="40" HorizontalContentAlignment="Center" &gt;&lt;/Button&gt;
  </code></pre>
  
  <p>In constructor I am setting the style like :</p>
  
  <pre><code>btn_bfx.Style = this.Resources["RoundCorner"] as Style;
  </code></pre>
  
  <p>later based on some condition I would like to change the style. </p>
  
  <p>The code is as below:</p>
  
  <pre><code>Style oldStyle = FindResource("RoundCorner") as Style;
  Style newStyle = new Style();
  newStyle.BasedOn = oldStyle;
  newStyle.TargetType = typeof(Button);
  foreach (var setter in oldStyle.Setters.ToList())
  {
      newStyle.Setters.Add(setter);
  }
  newStyle.Setters.Add(new Setter(BackgroundProperty, Brushes.CadetBlue));
  btn_bfx.Style = newStyle;
  </code></pre>
  
  <p>The newStyle is just adding background color to the oldStyle. But this new style is not being applied. I am still getting the style without background color.</p>