代码之家  ›  专栏  ›  技术社区  ›  Rachel

我可以为样式添加资源或资源字典吗?

  •  7
  • Rachel  · 技术社区  · 15 年前

    是否可以以样式定义ResourceDictionary?

    例如,假设我希望StackPanels有两种不同的样式,一种是所有的按钮都是蓝色的,另一种是红色的。这可能吗?

    有点像

    <Style x:Key="RedButtonsPanel" TargetType="{x:Type StackPanel}">
        <Setter Property="Orientation" Value="Horizontal" />
        <Setter Property="StackPanel.Resources">
            <Setter.Value>
                <ResourceDictionary>
                    <Style TargetType="{x:Type Button}">
                        <Setter Property="Background" Value="Red" />
                    </Style>
                </ResourceDictionary>
            </Setter.Value>
        </Setter>
    </Style>
    

    上面的代码失败,错误是Setter的属性值不能为空(即使它显然不是空的)。

    我可以做一些像

    <ResourceDictionary x:Key="RedButtons">
        <Style TargetType="{x:Type Button}">
            <Setter Property="Width" Value="100" />
            <Setter Property="Background" Value="Red" />
        </Style>
    </ResourceDictionary>
    
    <StackPanel Resources={StaticResource RedButtons} />
    

    不过,我想知道是否有办法将ResourceDictionary合并到样式中。

    2 回复  |  直到 14 年前
        1
  •  4
  •   Aaron McIver    15 年前

    StackPanel.Resources 不是 DependencyProperty 因此,我不相信你能在样式中设置该属性。

        2
  •  3
  •   Vadim Ovchinnikov    8 年前

    尝试添加 Style(s) 为每个人 TargetType DockPanel Style.Resources .

    我做了类似的事情 DockPanel公司 Style . 希望将所有按钮或分隔符添加到 DockPanel公司 以一致的方式被设计。

    下面是一个示例:

    <Style x:Key="DockPanelToolBarStyle" TargetType="{x:Type DockPanel}">
       <Style.Resources>
         <Style TargetType="Button" BasedOn="{StaticResource ButtonToolBarStyle}" />
         <Style TargetType="Separator" BasedOn="{StaticResource SeparatorToolBarStyle}" />
       </Style.Resources>
       <Setter Property="Height" Value="45"/>
       <Setter Property="Background" Value="{StaticResource ToolBarBrush}"/>
    </Style>
    
    推荐文章