(四)Style样式外部引用
一:右键添加资源字典命名为BaseButtonStyle
直接写入资源样式:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfTest"> <!--设置基础的Style--> <Style TargetType="Button"> <Setter Property="Background" Value="WhiteSmoke"/> <Setter Property="FontSize" Value="20"/> <Setter Property="Margin" Value="0,10,20,20"/> </Style> <!--定义特别的Style并引用继承基础的Button样式--> <Style x:Key="LoginStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Background" Value="Blue"/> </Style> <!--定义特别的Style并引用继承基础的Button样式--> <Style x:Key="QuitStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="Background" Value="Red"/> </Style> </ResourceDictionary>
二:在App.xaml中添加全局字典引用,注意source格式路径,如果有文件夹则填入文件夹路径
<Application x:Class="WpfTest.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfTest" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!--对Style进行全局引用--> <ResourceDictionary Source="/WpfTest;component/BaseButtonStyle.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
三:所有Xaml窗口都可以引用此样式
<Window x:Class="WpfTest.WindowStyle" 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="WindowStyle" Height="450" Width="800"> <Grid> <StackPanel> <Button Style="{DynamicResource LoginStyle}" Content="登录"/> <Button Style="{DynamicResource QuitStyle}" Content="退出"/> </StackPanel> </Grid> </Window>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报