前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WPF-样式Style

WPF-样式Style

作者头像
MaybeHC
发布2024-04-23 18:20:07
510
发布2024-04-23 18:20:07
举报
文章被收录于专栏:技术之路

Style

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

代码语言:javascript
复制
    <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的属性。

代码语言:javascript
复制
 <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

代码语言:javascript
复制
<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>

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Style
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档