Search code examples
wpfxamlbuttonspacing

Adding spaces between WPF controls


I have created two buttons using the following XAML code.

<Button x:Name="Button1" Width="100" Content="Button1" HorizontalAlignment="Left" VerticalAlignment="Top" ></Button>
                        <Button x:Name="Button2" Width="100" Content="Button2" HorizontalAlignment="Left" VerticalAlignment="Top" ></Button>

The two buttons are tightly touching each other. How to put some space between them?

Note: The buttons are located inside a stackpanel with Horizontal orientation.


Solution

  • Add a Margin to your buttons

    <Button Margin="10" x:Name="Button1" Width="100" Content="Button1" HorizontalAlignment="Left" VerticalAlignment="Top" ></Button>
    <Button Margin="10"  x:Name="Button2" Width="100" Content="Button2" HorizontalAlignment="Left" VerticalAlignment="Top" ></Button>
    

    The Margin will make sure there is at least that much space between each button and any other control

    Something you might find useful is that you can have different margin values for top, left, right and bottom so:

    Margin="10,0,10,0"
    

    Would space the buttons out horizontally but wouldn't make them any smaller vertically...