Spacing between child controls in WPF Grid

WpfLayoutGrid

Wpf Problem Overview


I have a set of Key/Value pairs I want to display on a WPF Window. I'm using a grid to lay them out like so:

<Grid Margin="4">
	<Grid.ColumnDefinitions>
		<ColumnDefinition Width="Auto"/>
		<ColumnDefinition/>
	</Grid.ColumnDefinitions>
	<Grid.RowDefinitions>
		<RowDefinition Height="Auto"/>
		<RowDefinition Height="Auto"/>
	</Grid.RowDefinitions>

	<Label Grid.Row="0" Grid.Column="0">Code</Label>
	<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Code}"/>

	<Label Grid.Row="1" Grid.Column="0">Name</Label>
	<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Name}"/>
</Grid>

However when I display this, the TextBoxes are squashed up with their top and bottom borders touching the TextBox above/below. What is the best way to add vertical space to the rows in this layout?

Wpf Solutions


Solution 1 - Wpf

Easiest way is to set a margin on the individual controls. Setting it on the TextBoxes should be enough, because once they're spaced out the Labels will set vertically in the center of each row and have plenty of space anyway.

You can set it once using a style:

<Grid Margin="4">
    <Grid.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Margin" Value="0,0,0,4" />
        </Style>
    </Grid.Resources>

    ...
</Grid>

This will add a 4-pixel margin to the bottom of any TextBox inside your grid.

Solution 2 - Wpf

Another nice approach can be seen here.

You create class for setting Margin property:

public class MarginSetter
{
    public static Thickness GetMargin(DependencyObject obj) => (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(nameof(FrameworkElement.Margin), typeof(Thickness),
            typeof(MarginSetter), new UIPropertyMetadata(new Thickness(), MarginChangedCallback));

    public static void MarginChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        // Make sure this is put on a panel
        var panel = sender as Panel;

        if (panel == null) return;

        panel.Loaded += Panel_Loaded;
    }

    private static void Panel_Loaded(object sender, EventArgs e)
    {
        var panel = sender as Panel;

        // Go over the children and set margin for them:
        foreach (FrameworkElement fe in panel.Children.OfType<FrameworkElement>())
            fe.Margin = GetMargin(panel);
    }
}

Now you have attached property behavior, so that syntax like this would work:

<StackPanel local:MarginSetter.Margin="5">
   <TextBox Text="hello" />
   <Button Content="hello" />
   <Button Content="hello" />
</StackPanel>

This is the easiest & fastest way to set Margin to several children of a panel, even if they are not of the same type. (I.e. Buttons, TextBoxes, ComboBoxes, etc.)

Solution 3 - Wpf

What about setting TextBox's VerticalAlignment to Center?

<Grid Margin="4">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>

                <Label Grid.Row="0" Grid.Column="0">Code</Label>
                <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Code}" VerticalAlignment="Center"/>

                <Label Grid.Row="1" Grid.Column="0">Name</Label>
                <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Name}" VerticalAlignment="Center"/>
            </Grid>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGrokysView Question on Stackoverflow
Solution 1 - WpfMatt HamiltonView Answer on Stackoverflow
Solution 2 - WpfElad KatzView Answer on Stackoverflow
Solution 3 - WpfNormanView Answer on Stackoverflow