#221 – Changing a Brush at Run-Time(在Run-Time的时候改变画刷)

来源:互联网 发布:用户行为分析 算法 编辑:程序博客网 时间:2024/05/01 09:29

我们可以在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的时候改变了SolidColorBrushColor 属性。

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/


0 0
原创粉丝点击