控件的样式
可以向窗口中添加一个按钮,然后对其样式进行改变。
<Grid>
<Button FontSize="30" Foreground="Blue" Content="press" Width="200" Height="40" />
</Grid>
需要多个按钮时,可以使用panel
<StackPanel>
<Button FontSize="30" Foreground="Blue" Content="press" Width="200" Height="40" />
<Button FontSize="30" Foreground="Blue" Content="press" Width="200" Height="40" />
<Button FontSize="30" Foreground="Blue" Content="press" Width="200" Height="40" />
</StackPanel>
当有很多按钮控件需要使用同样样式的时候,可以创建一个样式
如何创建样式:
创建样式需要在下 的 并且需要给每个样式下一个键值:
<Window.Resources>
<Style x:Key="defaultButtonStyle" TargetType="Button">
<Setter Property="FontSize" Value="25"/>
<Setter Property="Foreground" Value="red"/>
<Setter Property="Content" Value="hello"/>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<Button Style="{StaticResource defaultButtonStyle}" FontSize="30" Foreground="Blue" Content="press" Width="200" Height="40" />
<Button Style="{StaticResource defaultButtonStyle}" FontSize="30" Foreground="Blue" Content="press" Width="200" Height="40" />
<Button Style="{StaticResource defaultButtonStyle}" FontSize="30" Foreground="Blue" Content="press" Width="200" Height="40" />
</StackPanel>
</Grid>
需要注意,当引用样式的时候,如果button 重新覆写了样式,将会覆盖样式表中的样式,要想让样式表生效需要将重复的样式删除掉。这样才会显示样式:
<Window.Resources>
<Style x:Key="defaultButtonStyle" TargetType="Button">
<Setter Property="FontSize" Value="25"/>
<Setter Property="Foreground" Value="red"/>
<Setter Property="Content" Value="hello"/>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<Button Style="{StaticResource defaultButtonStyle}" Content="press" Width="200" Height="40" />
<Button Style="{StaticResource defaultButtonStyle}" FontSize="30" Foreground="Blue" Content="press" />
<Button Style="{StaticResource defaultButtonStyle}" Width="200" Height="40" />
</StackPanel>
</Grid>
样式的继承关系
样式之间也是可以继承的,需要使用到 BasedOn=""
如: BasedOn="{StaticResource baseButtonStyle}
<Window.Resources>
<Style x:Key="baseButtonStyle" TargetType="Button">
<Setter Property="FontSize" Value="25"/>
<Setter Property="Foreground" Value="red"/>
</Style>
<Style x:Key="defaultButtonStyle" TargetType="Button" BasedOn="{StaticResource baseButtonStyle}">
<Setter Property="Content" Value="hello"/>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<Button Style="{StaticResource defaultButtonStyle}" Content="press" Width="200" Height="40" />
<Button Style="{StaticResource defaultButtonStyle}" FontSize="30" Foreground="Blue" Content="press" />
<Button Style="{StaticResource defaultButtonStyle}" Width="200" Height="40" />
</StackPanel>
</Grid>