我们可以在Run-Time的时候改变Brush的外观属性,例如它的颜色,那么任何使用这个Bursh的控件也会自动的随着改变。
假如我们有若干个使用了SolidColorBrush 的控件
<Window.Resources>
<SolidColorBrush x:Key="magicBrush" Color="Red"/>
</Window.Resources>
<StackPanel>
<Button Content="Don't Push Me" Background="{StaticResource magicBrush}" Width="120" Margin="10"/>
<Label Content="Pull my finger!" Foreground="{StaticResource magicBrush}" HorizontalAlignment="Center"/>
<Ellipse Height="100" Width="200" Fill="{StaticResource magicBrush}" Margin="10"/>
</StackPanel>
上面的代码中定义了一个红色的
SolidColorBrush,而且有一个Button,一个Label和一个Ellipse使用了这个
SolidColorBrush 。
现在假设我们在Run-Time的时候改变了SolidColorBrush 的Color 属性。
SolidColorBrush magicBrush = (SolidColorBrush)this.Resources["magicBrush"];
magicBrush.Color = Colors.Purple;
我们会发现,所有使用这个SolidColorBrush 的控件的颜色也会马上随之改变。
这是因为SolidColorBrush 继承自Freezable 类,Freezable 支持Changed 事件,当画刷颜色改变的时候Changed 事件将被触发,而控件收到这个事件后就会重绘自己。
原文地址:https://wpf.2000things.com/2011/02/18/221-changing-a-brush-at-run-time/