【WPF】WPF(样式)

发布于:2025-07-07 ⋅ 阅读:(12) ⋅ 点赞:(0)

Window.Resources 当前窗体作用域资源

TargetType=“Button”

  使得当前窗体的组件类型都适配此样式
    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Background" Value="WhiteSmoke"></Setter>
            <Setter Property="Margin" Value="20,10"></Setter><!--左右20 上下10-->
        </Style>
    </Window.Resources>
        <StackPanel>
        <Button Content="登录"  />
        <Button Content="退出"/>
        <Button Content="忘记密码" />
        <Button Content="忘记密码" />
    </StackPanel>

在这里插入图片描述

x:Key=“loginStyle” 指定样式

    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Background" Value="WhiteSmoke"></Setter>
            <Setter Property="Margin" Value="20,10"></Setter><!--左右20 上下10-->
        </Style>
        <Style x:Key="QuitStyle" TargetType="Button">
            <Setter Property="Background" Value="Red"></Setter>
            <Setter Property="Width" Value="200"></Setter>
            <Setter Property="Height" Value="50"></Setter>
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button Content="登录"  />
        <Button Content="退出"  Style="{StaticResource QuitStyle}"/>
        <Button Content="忘记密码" />
        <Button Content="忘记密码" />
    </StackPanel>

在这里插入图片描述

BasedOn=“{ StaticResource {x:Type Button}}” 继承样式

  继承通用样式后设置样式会覆盖继承的样式
<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Background" Value="WhiteSmoke"></Setter>
            <Setter Property="Margin" Value="20,10"></Setter><!--左右20 上下10-->
        </Style>
        <Style x:Key="loginStyle" TargetType="Button" BasedOn="{ StaticResource {x:Type Button}}"> <!--继承通用设置-->
            <Setter Property="Background" Value="Green"></Setter>
            <!--覆盖通用设置-->
        </Style>
        <Style x:Key="QuitStyle" TargetType="Button">
            <Setter Property="Background" Value="Red"></Setter>
            <Setter Property="Width" Value="200"></Setter>
            <Setter Property="Height" Value="50"></Setter>
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button Content="登录" Style="{StaticResource loginStyle}" />
        <!--指定style-->
        <Button Content="退出"/>
        <Button Content="忘记密码" />
        <Button Content="忘记密码" />
    </StackPanel>
</Window>

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到