title: Changing XAML style dynamically in Code Behind so that controls applying that style also reflect the change
body: <p>I want to be able to set style properties (and values) from the .cs file in my WPF window. </p>
  
  <p>My problem is if I have 30 rectangles, all of which I want to have the same style (and I don't want to update all of them individually). I'd like to have them all set (in the xaml file) to the same style, and then update the style to look the way I'd like.</p>
  
  <p>Say I set the <code>Style = "key1"</code> in the Xaml for each rectangle. Then I want to be able to modify "key1" later so all the rectangles will reflect that change.</p>
  
  <p>I tried in <code>App.xaml</code></p>
  
  <pre><code>&lt;Application.Resources&gt;
      &lt;Style x:Key="key1" TargetType="Rectangle"&gt;
          &lt;Setter Property="Fill" Value="Red"/&gt;
      &lt;/Style&gt;
  &lt;/Application.Resources&gt;
  </code></pre>
  
  <p>In MainwWindows.xaml</p>
  
  <pre><code>&lt;StackPanel&gt;
      &lt;Rectangle Style="{StaticResource key1}" Height="200" Width="200" x:Name="rect1"/&gt;
      &lt;Button Click="Button_Click" Content="Click"/&gt;
  &lt;/StackPanel&gt;
  </code></pre>
  
  <p>In code behind</p>
  
  <pre><code>private void Button_Click(object sender, RoutedEventArgs e)
  {
      Style style = Application.Current.Resources["key1"] as Style;
      style.Setters.Add(new Setter(Rectangle.VisibilityProperty, Visibility.Collapsed));
  }
  </code></pre>
  
  <p>This updates the style but do not update the rectangles.</p>
  
  <p>Is this possible? Does anyone know how to do this? (An example would be greatly appreciated).</p>