我想在按钮中设置多种样式,特别是以下两种:
您可以基于Style2
创建Style1
,或者反之,然后将顶级style
应用于您的button
。
<Window.Resources>
<Style TargetType="Button" x:Key="Style1">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
<Style TargetType="Button" x:Key="Style2" BasedOn="{StaticResource Style1}">
<Setter Property="Background" Value="Green"/>
</Style>
但是,如果您不想更改您的两种样式中的任何一种(它们在其他地方也被使用),请按照此博客文章扩展您的按钮样式。
Style
。但是您可以通过使用Style.BasedOn
属性来“合并”样式。例如:<Style TargetType="Button" x:Key="style1">
<Setter Property="Background" Value="Red"/>
<!-- some other setters here -->
</Style>
<Style TargetType="Button" BasedOn="{StaticResource style1}">
<Setter Property="BorderBrush" Value="Green"/>
<Setter Property="BorderThickness" Value="2"/>
<!-- some othe setters maybe-->
</Style>
Button
背景设置为红色,边框刷为绿色。
第二个样式没有x:Key
属性。这意味着它会自动应用于每个Button
。您只能在一个ResourceDictionary
中定义一个这样的样式。
FrameworkElement
只能有一个Style
,但是样式可以互相BasedOn
。 - dkozlStaticResource
。BasedOn
不是DependencyProperty
,因此不能使用DynamicResource
。 - dkozlBasedOn
样式必须是可访问的。您最好合并字典,并包含带有AccentedSquareButtonStyle
的字典,以便您可以将其用作StaticResource
。 - dkozl