(三)Style样式
一:定义样式作用于按钮

<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"> <!--编写Style样式资源文件--> <Window.Resources> <!--编写Style样式作用于Button,则会应用于所有Button,指定其他Key样式后失去作用--> <Style TargetType="Button"> <Setter Property="Background" Value="Azure"/> <Setter Property="FontSize" Value="30"/> <Setter Property="Height" Value="50"/> <Setter Property="Width" Value="200"/> </Style> <!--编写Style样式指定Key,用于后续绑定--> <Style x:Key="LoginStyle" TargetType="Button"> <Setter Property="Background" Value="Azure"/> <Setter Property="FontSize" Value="30"/> <Setter Property="Height" Value="50"/> <Setter Property="Width" Value="200"/> </Style> <!--编写Style样式指定Key,用于后续绑定--> <Style x:Key="QuitStyle" TargetType="Button"> <Setter Property="Background" Value="Red"/> <Setter Property="FontSize" Value="30"/> <Setter Property="Height" Value="50"/> <Setter Property="Width" Value="200"/> </Style> </Window.Resources> <Grid> <!--Background="AliceBlue" FontSize="20" Height="50" Width="200"这些都是通用的属性,如果按钮需要设置相同则需要Style样式绑定,StaticResource静态资源--> <!--DynamicResource动态资源,如果代码改变资源属性则动态改变,静态则不会 --> <StackPanel> <Button Style="{StaticResource LoginStyle}" Content="登录"/> <Button Style="{StaticResource QuitStyle}" Content="退出"/> </StackPanel> </Grid> </Window>
二:我们还可以定义基础样式,并定义子样式引用基础样式

<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"> <!--编写Style样式资源文件--> <Window.Resources> <!--设置基础的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> </Window.Resources> <Grid> <!--Background="AliceBlue" FontSize="20" Height="50" Width="200"这些都是通用的属性,如果按钮需要设置相同则需要Style样式绑定,StaticResource静态资源--> <!--DynamicResource动态资源,如果代码改变资源属性则动态改变,静态则不会 --> <StackPanel> <Button Style="{StaticResource LoginStyle}" Content="登录"/> <Button Style="{StaticResource QuitStyle}" Content="退出"/> </StackPanel> </Grid> </Window>

浙公网安备 33010602011771号