在WPF中,自定义样式是其强大之处之一,它允许您完全控制UI元素的外观和行为,而无需修改其核心逻辑。这主要通过Style和ControlTemplate
一.样式Style
允许您为控件的属性设置预定义的值,并可以包含触发器来响应属性变化或事件。
主要属性组成部分:
TargetType :
最重要的属性,用于将样式映射到控件上,如
cs
TargetType="Button"
x:Key :
重要的属性:界面就是通过key来调用样式的
Setters
定义要设置的属性及其值。
Triggers
当某个条件(例如,属性值改变,或事件发生)满足时,应用一组
二.资源字典
这是最常见和推荐的方式,因为它允许样式在整个应用程序、窗口或用户控件中重用。
wpf的全局字典是App.xaml这个文件,直接修改这个文件可以修改全局样式,我们也可以使用自定义字典,右键项目--新建项---wpf---资源字典
新建一个.xaml资源字典文件,例如style.xaml
XML
<!-- Themes/ButtonStyles.xaml -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- TextBlock样式 -->
<Style x:Key="TextBlockStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Padding" Value="15,8"/>
<Setter Property="Cursor" Value="Hand"/>
</Style>
<!-- Button样式 -->
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="Background" Value="#FF6200EE"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Padding" Value="15,8"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Cursor" Value="Hand"/>
</Style>
</ResourceDictionary>
三.在窗口中使用自定义样式
界面中引入样式字典
XML
<Window x:Class="NX_API.HomePage"
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:NX_API"
mc:Ignorable="d"
Title="机械设计" Height="1050" Width="1450" Background="#7B68EE">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- 合并 DLL 内部的资源字典 -->
<ResourceDictionary Source="/NX_API;component/Resource/Style/style.xaml"/>
<!-- 注意:Source 路径格式为 /程序集名称;component/资源文件路径 -->
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
</Window>
调用样式命令
{StaticResource 样式的key}
XML
<TextBlock HorizontalAlignment="Left" Margin="10,20,0,0" TextWrapping="Wrap" Text="螺纹类型:" VerticalAlignment="Top"
Style="{StaticResource TextBlockStyle}" />
此时界面上的textbox控件就会显示我们自定义的样式,其他空间也是这样映射使用