- WPF Layout System: An Introduction
- WPF Layout: Size, Width and Height
- WPF Layout: Margins
- WPF Layout: Horizontal and Vertical Alignment
- WPF Layout: Content Alignments
- WPF Layout: Dealing with Percentage Size in WPF
- WPF Layout: Panels
- WPF Layout: Canvas
- WPF Layout: DockPanel
- WPF Layout: Grid
- WPF Layout: StackPanel
- WPF Layout: WrapPanel
- WPF Layout: Border
- WPF Layout: VirtualizingStackPanel
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.
- <Rectangle Name="Rectangle1" Fill="LightBlue"
- HorizontalAlignment="Left" VerticalAlignment="Top"
- Margin="20" Width="200" Height="100" />
- <Rectangle Name="Rectangle2" Fill="LightGreen"
- HorizontalAlignment="Left" VerticalAlignment="Top"
- 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.

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.
- Rectangle1.Margin = new Thickness(20);
- Rectangle2.Margin = new Thickness(50, 50, 0, 0);
Summary
In this article, I explained the margins of WPF elements. The next article of this series explains Alignment of WPF elements.

Santhakumar MunuswamyPosted Apr 25, 2015, 7:41 AM
Thanks for nice one sir
Shaili DashoraPosted Mar 2, 2015, 1:17 PM
Nice sir thanks