简介
这里以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】整理记录