#325 – Specifying a Margin Value in Code

You can set the Margin property on a control so that it has some extra room around its edges, within its container.

You’ll typically set the values for Margin in XAML, but you can also set a Margin value in code.  The type of the Margin property is Thickness, which is a struct having fields for margins along the left, top, right and bottom of a control.

You can specify a value for Margin by creating a new instance of the Thickness structure.

            double left = 5.0;
            double top = 10.0;
            double right = 2.0;
            double bottom = 20.0;
            lblName.Margin = new Thickness(left, top, right, bottom);

#282 – The Margin Property Stores a Thickness Value

The Margin property, used by many controls to specify a margin around the outside of the control, is inherited from the FrameworkElement class.  The Margin property’s type is Thickness, which is a structure.

The Thickness structure has four fields, defining the size of the margin along each edge of the control: Left, Top, Right, Bottom.  The value of each of these fields is specified in device independent WPF Units.

You can specify a Thickness value in XAML by listing the four values in a comma-separated string, in the following order: “left, top, right, bottom”.

	<Image Name="imgKlondike" Source="TractorSm.png" Margin="5,10,5,10"/>

You can also change the value of a Margin in code.  You can’t set individual fields in the margin, but you can set the property to a new instance of a Thickness.

            Thickness oldMargin = imgKlondike.Margin;

            imgKlondike.Margin = new Thickness(
                oldMargin.Left + 2.0,
                oldMargin.Top + 2.0,
                oldMargin.Right + 2.0,
                oldMargin.Bottom + 2.0);