Search code examples
c#wpfstylesdatatemplate

How to set style for ItemsPanel from outside?


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?


Solution

  • 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.