-----------------------------------------
需要加微信群
的加我微信z438679770,我邀请进群,切记备注 :进群!
---------------------------------------
WPF的样式需要显示声明继承,即使用Style的BasedOn属性。
我们先在资源中定义一个基样式:
<Style x:Key="baseButtonStyle" TargetType="Button">
<Setter Property="FontSize" Value="30"/>
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="Background" Value="Gray"/>
</Style>
然后我们定义两个继承自它的样式,分别为对应按钮baseButtonStyle1和baseButtonStyle2的样式:
<Style x:Key="baseButtonStyle1" TargetType="Button" BasedOn="{StaticResource baseButtonStyle}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="40"/>
</Style>
<Style x:Key="baseButtonStyle2" TargetType="Button" BasedOn="{StaticResource baseButtonStyle1}">
<Setter Property="Width" Value="120"/>
<Setter Property="Height" Value="50"/>
</Style>
BasedOn属性设为了我们先前设置的“baseButtonStyle”,各自追加了一些属性的设置。
现在在界面上添加三个按钮控件:
<Grid>
<StackPanel>
<Button Style="{StaticResource baseButtonStyle}" Content="hello"/>
<Button Style="{StaticResource baseButtonStyle1}" Content="hello"/>
<Button Style="{StaticResource baseButtonStyle2}" Content="hello"/>
</StackPanel>
</Grid>
现在界面效果如下:
可以看到,按钮继承了基样式中的背景和字体和字体颜色。
全部xaml如下:
<Window x:Class="WpfApp9.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:WpfApp9"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style x:Key="baseButtonStyle" TargetType="Button">
<Setter Property="FontSize" Value="30"/>
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="Background" Value="Gray"/>
</Style>
<Style x:Key="baseButtonStyle1" TargetType="Button" BasedOn="{StaticResource baseButtonStyle}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="40"/>
</Style>
<Style x:Key="baseButtonStyle2" TargetType="Button" BasedOn="{StaticResource baseButtonStyle1}">
<Setter Property="Width" Value="120"/>
<Setter Property="Height" Value="50"/>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<Button Style="{StaticResource baseButtonStyle}" Content="hello"/>
<Button Style="{StaticResource baseButtonStyle1}" Content="hello"/>
<Button Style="{StaticResource baseButtonStyle2}" Content="hello"/>
</StackPanel>
</Grid>
</Window>