WPF-样式Style

29 篇文章 4 订阅

Style

若我们要给多个控件设置多个相同的属性时,这时一个一个设置会显得很麻烦,这时使用Style给多个控件设置就显得很简便。
如果我要给一个button设置字体大小,字体等内容需要做如下设置

    <Window.Resources>
        <sys:Double x:Key="ButtonFontSize">18</sys:Double>
        <FontWeight x:Key="ButtonFontWeight">Bold</FontWeight>
        <FontFamily x:Key="ButtonFontFamily">Times New Roman</FontFamily>
    </Window.Resources>
<Button Margin="5" 
                FontWeight="{StaticResource ButtonFontWeight}" 
                FontSize="{StaticResource ButtonFontSize}" 
                FontFamily="{StaticResource ButtonFontFamily }">A Customized button</Button>

如果我要给另一个按钮设置相同属性时则需要复制这三条属性,如果有更多则每次都需要复制这三条。当出现更改时则需要更改每个button的属性。

 <Window.Resources>
        <sys:Double x:Key="ButtonFontSize">18</sys:Double>
        <FontWeight x:Key="ButtonFontWeight">Bold</FontWeight>
        <FontFamily x:Key="ButtonFontFamily">Times New Roman</FontFamily>
    </Window.Resources>
<Button Margin="5" 
                FontWeight="{StaticResource ButtonFontWeight}" 
                FontSize="{StaticResource ButtonFontSize}" 
                FontFamily="{StaticResource ButtonFontFamily }">A Customized button</Button>
<Button Margin="5" 
                FontWeight="{StaticResource ButtonFontWeight}" 
                FontSize="{StaticResource ButtonFontSize}" 
                FontFamily="{StaticResource ButtonFontFamily }">button</Button>

现在我使用Style

<Window.Resources>
        <Style x:Key="BigFontButtonStyle">
            <Setter Property="Control.FontFamily" Value="Times New Roman"></Setter>
            <Setter Property="Control.FontSize" Value="18"></Setter>
            <Setter Property="Control.FontWeight" Value="Bold"></Setter>
            <Setter Property="Control.Background">
                <Setter.Value>
                    <ImageBrush TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" Opacity="0.3" ImageSource="01cd6a5935737da8012193a3f0a784.jpg"/>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
<Button Margin="5" Style="{StaticResource BigFontButtonStyle}">Another Cystomized button</Button>

在Window.Resources设置好资源后,只用在button后加Style="{StaticResource BigFontButtonStyle}"便可以使用设置好的属性。

TargetType=""属性可以指定要使用该样式的控件类型,若该类型控件有不需要使用该Style的控件添加Style="{x:Null}"可不使用该样式。
也可以给样式中添加事件 例如<EventSetter Event="TextBlock.MouseEnter" Handler="element_MouseEnter"></EventSetter>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Maybe_ch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值