WPF样式

本文介绍了WPF样式,它类似于HTML中的CSS样式,设置细节较耗时。WPF样式分为属性样式、内联样式和引用样式(含页面级和应用程序级),并给出了各类型样式的示例代码,还提到可使用Baseon实现样式继承。

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

WPF样式类似于HTML中的CSS样式,设置外边距、内边距、颜色以及字体等细节,通过一系列封装所有这些细节的样式,然后再需要之处通过属性来应用样式。所以在设置WPF样式时,所花的时间也是比较多的。

WPF样式分为:

属性样式 直接通过UI元素的属性设置的样式

内联样式 通过在UI元素中嵌入style节点来设置样式

引用样式 定义在资源字典中的样式(页面级和应用程序级)

示例

属性样式,通过在TextBlock元素设置Width、Height、Margin等属性实现的简单样式

 <Grid>

        <!--属性样式-->

        <TextBlock Text="textbox" Width="200" Height="50"

                   Margin="40,40,40,40" HorizontalAlignment="Center"

                   VerticalAlignment="Center" Background="Green" FontSize="36"

                   TextAlignment="Center">

            

        </TextBlock>

</Grid>

内联样式,设置元素的style属性,也区分优先极,如果在元素里设置了内联样式又设置了属性的话会以属性样式为先

在TextBox里设置.style属性,TextBox里会使用.style的样式

 <!--属性样式-->

        <TextBox Text="textbox" Width="200" Height="50"

                 Margin="40,40,40,40" HorizontalAlignment="Center"

                 VerticalAlignment="Top" Background="SkyBlue" FontSize="36">

            <!--内联样式-->

            <TextBox.Style>

                <!--Property指定控件属性-->

                <Style TargetType="TextBox">

                    <Setter Property="Background" Value="Red"></Setter>

                    <Setter Property="BorderThickness" Value="3"></Setter>

                    <Setter Property="BorderBrush" Value="Yellow"></Setter>

                </Style>

            </TextBox.Style>

</TextBox>

引用样式,也就是资源定义,页面级引用的是整个页面都可以引用

<Window.Resources>

        <Style x:Key="pbStyle" TargetType="TextBlock">

            <Setter Property="FontSize" Value="40"></Setter>

            <Setter Property="Background" Value="Transparent"></Setter>

            <Setter Property="HorizontalAlignment" Value="Center"></Setter>

        </Style>

</Window.Resources>

<Grid>

        <TextBlock Style="{StaticResource pbStyle}" Text="页面引用" Height="60"></TextBlock>

</Grid>

应用程序级,需要在资源字典里定义,应用到整个程序

<Application.Resources>

        <Style x:Key="btn" TargetType="{x:Type Button}">

            <Setter Property="Background" Value="Black"></Setter>

            <Setter Property="FontSize" Value="24"></Setter>

            <Setter Property="Foreground" Value="Blue"></Setter>

            <Setter Property="Margin" Value="20"></Setter>

        </Style>

<Application.Resources/>

控件引用

<Button x:Name="button" Style="{StaticResource btn}" Content="Button" HorizontalAlignment="Left" Margin="122,10,0,0" VerticalAlignment="Top" Width="128" Height="57"/>

如果想在一个样式里面实现另一个样式的效果,就得使用Baseon来继承另一个样式

<Style x:Key="btn" TargetType="{x:Type Button}" BasedOn="{StaticResource btn}"/>

效果一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值