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

我们可以在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/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值