1

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?

Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • Move the implicit `Style` to `App.xaml`. – mm8 Oct 15 '19 at 13:33
  • Templates are not part of the visual tree, add x:Key to your style and then reference it in the StackPanel definition. – XAMlMAX Oct 15 '19 at 13:36
  • @mm8, thanks, this makes it working at run-time for above mcve. Any chance to scope style to a certain control resources? I want to have StackPanels green only inside a certain window or user control. – Sinatr Oct 15 '19 at 13:36
  • @XAMlMAX, idea was to set style on a parent container, so that children can inherit it. I didn't know templates are not a part of it, so they are not children, so this won't work. I need to pass style from outside somehow without setting it explicitly. App.xaml is not really an option as this has to be only done for a certain user control at most. – Sinatr Oct 15 '19 at 13:43

1 Answers1

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.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Using `BaseOn` is interesting option, thanks. Doing something like this in all templates in advance will let easy re-define style when needed without modifying children part (which can be inside some user control). Why `App.xaml` works without need to modify anything? Because it's a root of all? Is it possible to alter/fake root for `ItemsControl` somehow so that data template will use it? Custom resource dictionary is an acceptable solution if it would be possible. – Sinatr Oct 15 '19 at 13:56
  • https://stackoverflow.com/questions/9035878/implicit-styles-in-application-resources-vs-window-resources – mm8 Oct 15 '19 at 14:00
  • It depends on the scope but there is no "root" that you can set. – mm8 Oct 15 '19 at 14:22