WPF全局样式、控件模板(圆角Button)和资源字典
WPF全局样式、控件模板(圆角Button)和资源字典
- 在解决方案中添加资源字典
buttonStytle
,最好自定义个文件夹放里边。如图:
- 资源字典中写样式,注意基样式可以有key可以无key。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!--基类样式无key--> <Style TargetType="Button"> <Setter Property="Background" Value="Yellow"/> </Style> <!--注意BaseOn写法--> <Style TargetType="Button" x:Key="startButton" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Width" Value="200"/> </Style> <!--基类样式有key--> <Style TargetType="Button" x:Key="quitButtonBase"> <Setter Property="Background" Value="Blue" /> </Style> <!--注意BaseOn写法--> <Style TargetType="Button" x:Key="quitButton" BasedOn="{StaticResource quitButtonBase}"> <Setter Property="Width" Value="200"/> </Style> <ControlTemplate TargetType="Button" x:Key="roundButton"> <Border Background="{TemplateBinding Background}" CornerRadius="10"> <TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/> <!--这样也可以把按钮的文字属性拿过来--> <!--<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>--> </Border> </ControlTemplate>
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/WPFUI;component/style/buttonStyle.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
4. 控件引用样式 ```xaml <Window x:Class="WPFUI.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:local="clr-namespace:WPFUI" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Title="MainWindow" Width="800" Height="450" mc:Ignorable="d"> <Grid> <StackPanel> <Button Content="开始" Style="{StaticResource startButton}" /> <Button Content="结束" Style="{StaticResource quitButton}" /> <Button Width="100" Height="50" Background="#0078d4" Content="自定义模板" FontSize="16" Template="{StaticResource roundButton}" /> </StackPanel> </Grid> </Window>
- 结束。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?