如何从外部设置ItemsPanel的样式? [英] How to set style for ItemsPanel from outside?

查看:68
本文介绍了如何从外部设置ItemsPanel的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一种样式,使所有 StackPanel 变为绿色:

I define a style to make all StackPanel green:

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

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

But if I use StackPanel as panel template then it's NOT green:

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

为什么?如何使其也变绿色?

Why? How to make it also green?

推荐答案

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

Either move the implicit Style to App.xaml or add resource that is based on the implicit Style to the ItemsPanelTemplate:

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

不从 Control 继承的类型如果您不执行任何隐式样式,则不会使用。

Types that don't inherit from Control won't pick up implicit styles if you don't do any of this.

这篇关于如何从外部设置ItemsPanel的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆