How to set margin for inner controls of WrapPanel

Andrey Tagaew picture Andrey Tagaew · Jan 11, 2011 · Viewed 29.7k times · Source

Here is an example that I'm using:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <WrapPanel Orientation="Horizontal" TextElement.FontSize="30" TextElement.FontStyle="Italic"  >
        <Button Content="test1" Margin="10,0" Padding="10,10" />
        <Button Content="test2" Margin="10,0" Padding="10,10" />
        <Button Content="test3" Margin="10,0" Padding="10,10" />
        <Button Content="test4" Margin="10,0" Padding="10,10" />
        <Button Content="test5" Margin="10,0" Padding="10,10" />
    </WrapPanel>
</StackPanel>

As you can see, my wrap panel has several buttons. Each button has the same margin and padding.

The question is, is there a way of setting margin and padding for wrap panel, so each element inside the wrap panel may use it values?

For setting inner element's font, i may use "TextElement" attached property provider. Is there similar way how i can set margin and padding for inner controls?

This make the code shorter and let me specify Margin and Padding only one time instead of setting it for each control in the panel.

Thank you!

Answer

gehho picture gehho · Jan 11, 2011

The solution provided by James Hay is the easiest way to achieve your desired result.

However, there are other possible solutions:

  1. You could implement your own attached property/behavior for a WrapPanel which sets the Margin and/or Padding for all its children. See this CodeProject article by Josh Smith for details.
  2. You could create your own panel which inherits from WrapPanel and just adds the required properties and overrides the appropriate methods, so that the Margin/Padding is set for all child elements.
  3. You could also move the Style definition from the Window.Resources to the WrapPanel.Resources, remove the x:Key attribute from the Style, and remove the Style="{StaticResource ButtonStyle}" from all Buttons. This way, the Style is applied to all Buttons which are children of the WrapPanel. If you also have other controls as children, you could change the TargetType for the Style to an appropriate common base type (e.g. FrameworkElement):

<StackPanel>
  <WrapPanel Orientation="Horizontal">
    <WrapPanel.Resources>
      <Style TargetType="{x:Type Button}">
        <Setter Property="Margin" Value="10,0" />
        <Setter Property="Padding" Value="10,10" />
      </Style>
    </WrapPanel.Resources>

    <Button Content="test1" />
    <Button Content="test2" />
    <Button Content="test3" />
    <Button Content="test4" />
    <Button Content="test5" />
  </WrapPanel>
</StackPanel>

Note, however, that this will influence all Button instances within the WrapPanel, not only its direct children!