如果我们的程序有三个这样的按键,一般我们会这样写
<StackPanel> <!--按键的背景色为Azure蔚蓝色背景色为Coral珊瑚色字体为Arial加粗字体大小为16--> <Button Content="Button1" Background="Azure" Foreground="Coral" FontFamily="Arial" FontWeight="Bold" FontSize="16" /> <Button Content="Button2" Background="Azure" Foreground="Coral" FontFamily="Arial" FontWeight="Bold" FontSize="16" /> <Button Content="Button3" Background="Azure" Foreground="Coral" FontFamily="Arial" FontWeight="Bold" FontSize="16" /> </StackPanel>
但是如果我们的程序有很多这样的按键都这样写会显得很冗余,于是我们可以定义一个样式Style,让所有按键都用这种样式
<Window.Resources> <Style x:Key="ButtonStyle"> <!--按键的背景色为Azure蔚蓝色背景色为Coral珊瑚色字体为Arial加粗字体大小为16--> <Setter Property="Control.FontFamily" Value="Arial"></Setter> <Setter Property="Control.Background" Value="Azure"></Setter> <Setter Property="Control.Foreground" Value="Coral"></Setter> <Setter Property="Control.FontWeight" Value="Bold"></Setter> <Setter Property="Control.FontSize" Value="16"></Setter> </Style> </Window.Resources> <StackPanel> <Button Content="Button1" Style="{StaticResource ButtonStyle}" /> <Button Content="Button2" Style="{StaticResource ButtonStyle}" /> <Button Content="Button3" Style="{StaticResource ButtonStyle}" /> </StackPanel>
这样代码就会显得简洁一些,细心的小伙伴儿发现所有的按键都用Style="{StaticResource ButtonStyle}"来指定样式,感觉还是略有一点冗余,那我们还可以继续让代码简洁一些,把
<Style x:Key="ButtonStyle">样式里的键值换成目标类型TargetTpye="Button",
<Window.Resources> <Style TargetType="Button"> <!--按键的背景色为Azure蔚蓝色背景色为Coral珊瑚色字体为Arial加粗字体大小为16--> <Setter Property="Control.FontFamily" Value="Arial"></Setter> <Setter Property="Control.Background" Value="Azure"></Setter> <Setter Property="Control.Foreground" Value="Coral"></Setter> <Setter Property="Control.FontWeight" Value="Bold"></Setter> <Setter Property="Control.FontSize" Value="16"></Setter> </Style> </Window.Resources> <StackPanel> <Button Content="Button1" /> <Button Content="Button2" /> <Button Content="Button3" /> </StackPanel>
这样三个按键的代码就非常简洁了,但是有的小伙伴儿就想让第一个和第三个按键用上面的样式,第二个不适用样式,我们可以这样该
<Window.Resources> <Style TargetType="Button"> <!--按键的背景色为Azure蔚蓝色背景色为Coral珊瑚色字体为Arial加粗字体大小为16--> <Setter Property="Control.FontFamily" Value="Arial"></Setter> <Setter Property="Control.Background" Value="Azure"></Setter> <Setter Property="Control.Foreground" Value="Coral"></Setter> <Setter Property="Control.FontWeight" Value="Bold"></Setter> <Setter Property="Control.FontSize" Value="16"></Setter> </Style> </Window.Resources> <StackPanel> <Button Content="Button1" /> <Button Content="Button2" Style="{x:Null}" /> <Button Content="Button3" /> </StackPanel>
效果如下