【问题标题】:How to set style for ItemsPanel from outside?如何从外部设置 ItemsPanel 的样式?
【发布时间】:2019-10-15 13:22:18
【问题描述】:

我定义了一个样式让所有StackPanel变成绿色:

<Window.Resources>
    <Style TargetType="StackPanel">
        <Setter Property="Background" Value="Green" />
    </Style>
</Window.Resources>

但如果我使用StackPanel 作为面板模板,那么它不是绿色的:

<UniformGrid>
    <StackPanel /><!-- this one is green -->
    <ItemsControl>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel /><!-- this one is not -->
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</UniformGrid>

为什么?如何让它也变绿?

【问题讨论】:

  • 将隐式 Style 移动到 App.xaml
  • 模板不是可视化树的一部分,请将 x:Key 添加到您的样式中,然后在 StackPanel 定义中引用它。
  • @mm8,谢谢,这使它在运行时为上述 mcve 工作。有没有机会将样式范围限定为某个控制资源?我希望 StackPanels 仅在某个窗口或用户控件内变为绿色。
  • @XAMlMAX,想法是在父容器上设置样式,以便子容器可以继承它。我不知道模板不是其中的一部分,所以它们不是孩子,所以这行不通。我需要以某种方式从外部传递样式而不明确设置它。 App.xaml 并不是一个真正的选项,因为最多只能为某个用户控件执行此操作。

标签: c# wpf styles datatemplate


【解决方案1】:

要么将隐式Style 移动到App.xaml,要么将基于隐式Style 的资源添加到ItemsPanelTemplate

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsPanelTemplate.Resources>
                <Style TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}" />
            </ItemsPanelTemplate.Resources>
            <StackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

如果您不这样做,不从 Control 继承的类型将不会选择隐式样式。

【讨论】:

  • 使用BaseOn 是一个有趣的选项,谢谢。提前在所有模板中执行此类操作可以在需要时轻松重新定义样式,而无需修改子部分(可以在某些用户控件中)。为什么App.xaml 不需要修改任何东西就可以工作?因为它是一切的根源?是否可以以某种方式更改/伪造ItemsControl 的根,以便数据模板使用它?如果可能的话,自定义资源字典是一个可接受的解决方案。
  • 取决于范围,但没有可以设置的“root”。
猜你喜欢
  • 2014-07-15
  • 2013-08-28
  • 1970-01-01
  • 2015-09-16
  • 2022-12-31
  • 1970-01-01
相关资源
最近更新 更多