全局样式和资源字典
- 在解决方案中添加资源字典
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> </ResourceDictionary>
- App.xaml中引用资源字典,
<ResourceDictionary Source="/WPFUI;component/资源字典路径" />
<Application x:Class="WPFUI.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFUI" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/WPFUI;component/style/buttonStyle.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
- 控件引用样式
<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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WPFUI" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <StackPanel> <Button Content="开始" Style="{StaticResource startButton}"/> <Button Content="结束" Style="{StaticResource quitButton}"/> </StackPanel> </Grid> </Window>
- 结束。