How to set style for ItemsPanel from outside?

半世苍凉 提交于 2020-01-05 07:08:56

问题


I define a style to make all StackPanel green:

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

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?


回答1:


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>

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



来源:https://stackoverflow.com/questions/58395780/how-to-set-style-for-itemspanel-from-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!