I want to be able to set style properties (and values) from a .cs file in my WPF window.
My problem is that I have 30 rectangles, all of which I want to have the same style (and I don't want to update them all separately). I would like all of them to be installed (in the xaml file) in the same style, and then updated the style to look as I would like.
Say I set Style = "key1" in Xaml for each rectangle. Then I want to be able to modify "key1" later, so all the rectangles reflect this change.
I tried in App.xaml
<Application.Resources> <Style x:Key="key1" TargetType="Rectangle"> <Setter Property="Fill" Value="Red"/> </Style> </Application.Resources>
In MainwWindows.xaml
<StackPanel> <Rectangle Style="{StaticResource key1}" Height="200" Width="200" x:Name="rect1"/> <Button Click="Button_Click" Content="Click"/> </StackPanel>
In 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)); }
This updates the style but does not update the rectangles.
Is it possible? Does anyone know how to do this? (An example would be greatly appreciated).
Nikhil Agrawal
source share