Search code examples
wpfxamlstackpanel

Making all images be of the same size and margin


I noticed that I've got a few images in a stack panel and every such has exactly the same size, margin, alignment etc. set to it. I don't want to create a global resource for style. Is it possible to have a local style declared in this specific panel and only for the images (TargetType is enough in this case)?

I'd like something along this solution with the exception that I don't use the global style resource.

<StackPanel.Resources>
  <Style TargetType="Image">
    <Setter Property="Width" Value="24" />
    ...
  </Style>
</StackPanel.Resources>
<Image Source="{StaticResource Poof}"
         VerticalAlignment="Top"
         ...
         Margin="20,20,20,0" />

Solution

  • Just put the style in the resources for the panel, and it will apply to all items of that type, inside the panel.

    For example:

    <StackPanel>
        <StackPanel.Resources>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Width" Value="200" />
            </Style>
        </StackPanel.Resources>
        <TextBox  Margin="20" />
        <TextBox  Margin="20" />
        <TextBox  Margin="20" />
        <TextBox  Margin="20" />
    </StackPanel>
    

    Results in all the text boxes having a width of 200 units.

    Unless, you override the style with a setting on the individual items. Perhaps you are doing that?