WPF中Style样式设置的几种方法

本文介绍了在WPF中通过XAML为Button设置全局样式、针对不同场景创建不同样式的两种方法,以及如何通过继承基础样式实现代码复用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

这里以button按钮为例,简单描述Style设置样式的几种方式

1、设置全局样式

通过在 <Window.Resources>标签下设置button样式,这样所有的button按钮都默认使用该设定的样式

    <Window.Resources>
        <Style TargetType="Button"><!--控件类型-->
            <Setter Property="Background" Value="Red"/><!--设定样式值-->
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="Height" Value="50"/>
            <Setter Property="Width" Value="300"/>
        </Style>
    </Window.Resources>
    
    <StackPanel>
        <Button  Content="登录"/>
        <Button Content="退出"/>
        <Button Content="忘记密码"/>
    </StackPanel>

运行效果

2、设置不同button样式

在使用中,可能不同地方的按钮需要设置不同的属性,可以通过给样式设置标识符的方式,设置button按钮的不同样式

    <Window.Resources>
        <Style x:Key="LoginStyle" TargetType="Button"><!--通过x:Key给该样式添加一个唯一的标识符-->
            <Setter Property="Background" Value="Green"/>
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="Height" Value="50"/>
            <Setter Property="Width" Value="300"/>
        </Style>

        <Style x:Key="QuitStyle" TargetType="Button">
            <Setter Property="Background" Value="Red"/>
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="Height" Value="50"/>
            <Setter Property="Width" Value="300"/>
        </Style>
    </Window.Resources>
    
    <StackPanel>
        <Button Style="{StaticResource LoginStyle}" Content="登录"/><!--StaticResource 代表静态资源-->
        <Button Style="{StaticResource QuitStyle}" Content="退出"/>
        <Button Content="忘记密码"/>
    </StackPanel>

运行效果图
运行效果

3、抽取相同属性

有时在设置属性的时候,不同按钮的属性虽然不同,但是有部分属性是相同的,可以将这部分相同的属性单独提取出来进行设置。

    <Window.Resources>

        <Style TargetType="Button"><!--基础样式-->
            <Setter Property="Background" Value="WhiteSmoke"/>
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="Margin"  Value="20,10"/>
        </Style>

        <Style x:Key="LoginStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"><!--继承基础的button样式-->
            <Setter Property="Background" Value="Green"/>
        </Style>

        <Style x:Key="QuitStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="Background" Value="Red"/>
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button Style="{StaticResource LoginStyle}" Content="登录"/>
        <Button Style="{StaticResource QuitStyle}" Content="退出"/>
        <Button Content="忘记密码"/>
    </StackPanel>

运行效果图
参考说明:
内容根据B站丑萌气质狗老师视频【WPF入门教程 Visual Studio 2022】整理记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值