tags:

views:

2566

answers:

2

i assumed that the C# margin property had a meaning like in CSS - the spacing around the outside of the control. But Margin values seem to be ignored to matter what values i enter.

Then i read on the SDK:

Setting the Margin property on a docked control has no effect on the distance of the control from the the edges of its container.

Given that i'm placing controls on forms, and perhaps docking them, what does the Margin property get me?

+2  A: 

The margin property is used by whatever layout engine your control host (Panel, for example) is using, in whatever way that layout engine sees fit. However, it is best used for spacing just as you assume. Just read the documentation for that specific layout engine.

It can be very handy when using a FlowLayoutPanel or TableLayoutPanel, for example - to either reduce the default padding or space things out a bit. Obviously, if you write a custom layout provider, you can use Margin however you see fit.

Philip Rieck
+2  A: 

Like Philip Rieck said, the margin property is only respected by container controls that perform layout. Here's an example that makes it fairly clear how the TableLayoutPanel respects the Margin property:

using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            TableLayoutPanel pnl = new TableLayoutPanel();
            pnl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
            pnl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
            pnl.Dock = DockStyle.Fill;
            this.Controls.Add(pnl);

            Button btn1 = new Button();
            btn1.Text = "No margin";
            btn1.Dock = DockStyle.Fill;

            Button btn2 = new Button();
            btn2.Margin = new Padding(25);
            btn2.Text = "Margin";
            btn2.Dock = DockStyle.Fill;

            pnl.Controls.Add(btn1, 0, 0);
            pnl.Controls.Add(btn2, 1, 0);
        }
    }
}

I believe the only .NET 2.0 built-in controls that respect this property are FlowLayoutPanel and TableLayoutPanel; hopefully third-party components respect it as well. It has basically no effect in other scenarios.

OwenP