WPF Layout: Margins

Proper layout and positioning are a vital part of interactive, high-performance and user-friendly Windows applications. This series of articles explains the layout process in WPF. The series began with an understanding of the WPF layout process. The next part of this series will cover the basics of layout and positioning such as size, margin, padding and alignment of elements. Later in this series, I will cover various panels and related parent controls available in WPF.

Table of Contents

Introduction

In the previous article, WPF Layout: Size, Width and Height, I explained how to manage the size of elements. Margins are another vital piece of the layout system. This article focuses on the margins only.

Margin

The margin is the space between an element and the parent element or other adjacent element on the same parent element. The margin adds extra space around the outside edges of an element.

The Margin property of FrameworkElement represents the margin of an element. It is a type of Thickness structure. The Thickness structure has the four properties Left, Top, Right and Bottom. You can either pass a single double value or four double values. When a single double value is passed to a Thickness, it applies to all four properties of the Thickness structure. If all four values of Thickness are passed, they apply to the Left, Top, Right and Bottom properties respectively.

The code snippet in Listing 1 creates two rectangles and sets the margin of the first rectangle by passing only one value 20 that sets the margin for all the four directions left, top, bottom and right to 20 each. The margin for the second rectangle is set to 50,50,0,0.

  1. <Rectangle Name="Rectangle1" Fill="LightBlue"    
  2.    HorizontalAlignment="Left" VerticalAlignment="Top"    
  3.    Margin="20" Width="200" Height="100" />    
  4. <Rectangle Name="Rectangle2" Fill="LightGreen"    
  5.    HorizontalAlignment="Left" VerticalAlignment="Top"    
  6.    Margin="50,50,0,0" Height="100" Width="200" /> 

Listing 1

The output of Listing 1 looks as in Figure 1. In Figure 1, you see two rectangles. The Blue rectangle has the margin set to 20,10,10,20. That shows that this extra space is added between the starting point (left corner) of the parent control and the rectangle.

 
                                    Figure 1

Similar to the Width and Height, the units of the Margin value can be set using px, in, cm and pt. The code snippet in Listing 2 sets the Margin properties at runtime by creating a Thickness object.
  1. Rectangle1.Margin = new Thickness(20);    
  2. Rectangle2.Margin = new Thickness(50, 50, 0, 0); 
Listing 2

Summary


In this article, I explained the margins of WPF elements. The next article of this series explains Alignment of WPF elements.

Up Next
    Ebook Download
    View all
    Learn
    View all