Change a style dynamically in WPF

后端 未结 2 1350
灰色年华
灰色年华 2020-12-09 10:03

Is there a way to change(and apply) a style dynamically in WPF?

Say I have the style declared in XAML:

    
...


    
    
    
    

Now to change the color of all shapes that use the "MyShapeStyle" style, you can do the following from your code-behind:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Random r = new Random();
    this.Resources["MyFillBrush"] = new SolidColorBrush(Color.FromArgb(
          0xFF, 
          (byte)r.Next(255), 
          (byte)r.Next(255), 
          (byte)r.Next(255)));
}

The thing that makes this work is the fact that you use a DynamicResource for the brush reference in your style - this tells WPF to monitor that resource for changes. If you use a StaticResource instead, you won't get this behavior.

提交回复
热议问题