一:右键添加资源字典命名为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>
标签:Style,样式,文件夹,引用,添加,字典 From: https://www.cnblogs.com/Peretsoft/p/18442238