What is the easy way to set spacing between items in StackPanel?

Related searches

Is there an easy way to set default space between items inside StackPanel so I'll don't have to set Margin property on each item?

if all the controls are the same then do as IanR suggested and implement a Style that catches that control. if it's not then you can't create a default style to a base class because it just won't work.

the best way for situations like these is to use a very neat trick - attached properties (aka Behaviors in WPF4)

you can create a class that has an attached property, like so:

public class MarginSetter
    public static Thickness GetMargin(DependencyObject obj)
        return (Thickness)obj.GetValue(MarginProperty);

    public static void SetMargin(DependencyObject obj, Thickness value)
        obj.SetValue(MarginProperty, value);

    // Using a DependencyProperty as the backing store for Margin.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MarginProperty =
        DependencyProperty.RegisterAttached("Margin", typeof(Thickness), typeof(MarginSetter), new UIPropertyMetadata(new Thickness(), CreateThicknesForChildren));

    public static void CreateThicknesForChildren(object sender, DependencyPropertyChangedEventArgs e)
        var panel = sender as Panel;

        if (panel == null) return;

        foreach (var child in panel.Children)
            var fe = child as FrameworkElement;

            if (fe == null) continue;

            fe.Margin = MarginSetter.GetMargin(panel);


now, to use it, all you need to do is to attach this attached property to any panel you want, like so:

<StackPanel local:MarginSetter.Margin="10">
    <Button Content="hello " />
    <Button Content="hello " />
    <Button Content="hello " />
    <Button Content="hello " />

Completely reusable of course.

StackPanel How to give spacing between child controls, I am new to SL, i have a simple question about StackPanel, how we can set the spacing between child controls of StackPanel? between each child without having to set that margin value on each child element individually. StackPanel is a layout panel that arranges child elements into a single line that can be oriented horizontally or vertically. By default, StackPanel stacks items vertically from top to bottom in the order they are declared. You can set the Orientation property to Horizontal to stack items from left to right.

I use a transparent separator, which works well:

<Separator Opacity="0" Height="20"/>

You can of course use margins but then if you want to change the margins you have to update all of the elements.

The separator can even be styled in a static resource.

An attached property could do it too but I think it's overkill.

How to space StackPanel items in XAML (has no Padding property , I came upon the issue of how to space items in a StackPanel. 29/what-is-the- easiest-way-to-set-spacing-between-items-in-stackpanel.aspx. Paragraph spacing controls how much space comes before and after the paragraph. In Word, line spacing is most commonly measured in multiples of whatever font size the paragraph is using. For example, say you’re using a 12 point font for the text in your paragraph. If you choose single line spacing, the space between lines will be 12 points

The accepted answer doesn't work anymore. But I used that answer and the blog the author of that answer (Elad Katz) to make a working code (tested in .Net Core) that I reproduce here:

    public static class EstablecedorMargen { 

    public static Thickness GetMargen(DependencyObject objeto) => objeto != null ? (Thickness)objeto.GetValue(PropiedadMargen) : new Thickness();

    public static void SetMargen(DependencyObject objeto, Thickness value) => objeto?.SetValue(PropiedadMargen, value);

    public static readonly DependencyProperty PropiedadMargen 
        = DependencyProperty.RegisterAttached("Margen", typeof(Thickness), typeof(EstablecedorMargen), new UIPropertyMetadata(new Thickness(), Cambió));

    public static void Cambió(object sender, DependencyPropertyChangedEventArgs e) {
        if (!(sender is Panel panel)) return;
        panel.Loaded += new RoutedEventHandler(EstablecerMargenControlesHijos);

    public static void EstablecerMargenControlesHijos(object sender, RoutedEventArgs e) {

        if (!(sender is Panel panel)) return;
        foreach (var hijo in panel.Children) {
            if (!(hijo is FrameworkElement feHijo)) continue;
            feHijo.Margin = GetMargen(panel);



Then you use:

   <StackPanel local:EstablecedorMargen.Margen="10" >          
            <Button Content="1" />
            <Button Content="2" />
            <Button Content="3" />

New Spacing property in StackPanel, You can use it to set the amount of space between each child element. The StackLayout control of Xamarin Forms already had this property. si toutes les commandes sont les mêmes, alors faites comme IanR l'a suggéré et mettez en place un Style qui saisit cette commande. si ce n'est pas le cas, vous ne pouvez pas créer un style par défaut à une classe de base parce que cela ne fonctionnera pas.

I find that creating a grid inside the stack panel, then adding the desired number of columns (or rows) as follows:

    <StackPanel Grid.Row="1" Grid.Column="0" Height="34" Width="698" Margin="10,5,10,10" Orientation="Horizontal"  HorizontalAlignment="Center" VerticalAlignment="Center" >
        <Grid Width="698" Margin="0,0,0,0">
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            <Button x:Name="StartButton" Content="Start" Grid.Row="0" Grid.Column="0" Style="{StaticResource 3DButton}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="70" Click="StartButton_Click" />
            <Button x:Name="HelpButton"  Content="Help"  Grid.Row="0" Grid.Column="1" Style="{StaticResource 3DButton}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="70" Click="HelpButton_Click"  />
            <Button x:Name="ExitButton"  Content="Exit"  Grid.Row="0" Grid.Column="2" Style="{StaticResource 3DButton}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="70" Click="ExitButton_Click" Foreground="Red" />

Space Children In A Panel, How to apply spacing to all children in a panel. The previous version of this article defined a control (called Spacer ) that inherited StackPanel . child elements --> </Controls:Spacer> lots of child elements with same margin (yuck !) OnSpacingChanged)); public static void SetSpacing(Panel d,� Advanced Item Appearance Customization. An obvious visual problem with our UI so far is the lack of sufficient spacing around and between items. Of course, we could address this by adding margins to the Grid of each DataTemplate, but that would result in duplicate code and would couple our templates more tightly to a specific context. If we

Alignment, Margins and Padding, The following example describes how to create the layout in the preceding A Border element encapsulates a parent StackPanel , with a Padding value of 15� This site uses cookies for analytics, personalized content and ads. By continuing to browse this site, you agree to this use. Learn more

How to get StackPanel's children to fill maximum space downward? (4) I simply want flowing text on the left, and a help box on the right. The help box should extend all the way to the bottom. If you take out the outer StackPanel below it works great.

The first column has a Width of "3*", while the second has "5*", dividing the horizontal space between the two columns at a ratio of 3:5. In the same way, the two rows have a Height of "2*" and "*" respectively, so the Grid allocates two times as much space for the first row as for the second ("*" is the same as "1*").

  • I would say Margin is the easiest way to go here... are they typically items of the same type? You can use implicit styles to set the Margin for each item...
  • Maybe I can use styles to set Margin for some base type? 'Control' for example
  • Also see the accepted answer here: stackoverflow.com/questions/932510/…
  • The only problem is that it works statically: if you were adding/removing children once the panel has been instantiated, that won't work.
  • Your attached behavior could maybe subscribe to LayoutUpdated, and set the correct margin for new items as needed.
  • At runtime CreateThicknesForChildren event is invoked befora any children are added. How to fix this code so it'll work not only on designer?
  • register to one of the events of the panel that would happen after the children has already been added. i'm guessing Loaded might do the trick.
  • How conveniently cumbersome is WPF in comparison to HTML and CSS (LESS, SASS) when it comes to markup.
  • @Microsoft, too bad this is not supported on UWP... :'(
  • How do I use this? Do I have to manual add a Seperator element after each child element? I don't see how this is better than setting the Margin property directly each child item. Am I missing something?
  • You could just omit the stackpanel and get the same effect. The Grid will stretch to its parent by default, by the way. Giving it a fixed width is unnecessary, and so a bad idea, as the parent may be resized later. WPF layouts use a lot of auto-sizing and stretching to parents.