如何为一个控件定义多个样式?

5
我想在按钮中设置多种样式,特别是以下两种:

每个FrameworkElement只能有一个Style,但是样式可以互相 BasedOn - dkozl
你需要使用 StaticResourceBasedOn 不是 DependencyProperty,因此不能使用 DynamicResource - dkozl
如果我进行修改:BasedOn =“{StaticResource AccentedSquareButtonStyle}”,编译器会将所有结构都标出并显示此错误:您只能依赖于具有目标基FrameworkElement类型的样式。 - Bender
BasedOn样式必须是可访问的。您最好合并字典,并包含带有AccentedSquareButtonStyle的字典,以便您可以将其用作StaticResource - dkozl
这个回答解决了你的问题吗?在WPF中,有没有一种方法可以将两个样式合并到一个控件中? - StayOnTarget
2个回答

7

您可以基于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="{DynamicResource AccentedSquareButtonStyle}" 是 Mahapp metro 的一部分。我在我的窗口资源中只定义了 Style="{StaticResource VisibleAnimation}"。 - Bender
好的,请基于 AccentedSquareButtonStyle 创建 VisibleAnimation 样式,并将 VisibleAnimation 样式应用到您的按钮上。 - SamTh3D3v
BaseOn 需要一个 StaticResource,它不支持动态资源,并且您不能创建一个基于针对按钮的样式来定位 FramworkElement 的样式! - SamTh3D3v
由于您无法更改AccentedSquareButtonStyle样式,因此您的VisibleAnimation样式也应该针对一个按钮。 - SamTh3D3v
好的,我已经创建了两种样式 ;) - Bender
提示:仅当x:Key = ...在TargetType = ...之前时才起作用!!!WTF... - IngoB

2
您只能向控件设置一种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>

第二种样式“合并”了他的setter和从它继承的样式的setter。因此,应用第二种样式将Button背景设置为红色,边框刷为绿色。 第二个样式没有x:Key属性。这意味着它会自动应用于每个Button。您只能在一个ResourceDictionary中定义一个这样的样式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接