user-controlscustom-controlswindows-forms-designernested-controls

Designer messes up location and size of a Custom UserControl child container that is design enabled


When I put this control on to a form, change it's size and location, save it and close the form. After opening it, location and size are not the same, but in .Designer.cs it's exactly how I set it.

I can't find a solution to this problem, not even someone mentioning it.

This is a simple example of a custom control I am using:

[Designer(typeof(myControlDesigner1))]
public partial class UserControl1 : UserControl
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    [TypeConverter(typeof(Panel))]
    [MergableProperty(false)]
    public System.Windows.Forms.Panel Panel
    {
        get
        {
            return pnlWorkingArea;
        }

        set
        {
            pnlWorkingArea = value;
        }
    }

    public UserControl1()
    {
        InitializeComponent();
    }
}

public class myControlDesigner1 : ControlDesigner
{
    public override void Initialize(IComponent component)
    {
        base.Initialize(component);
        UserControl1 bc = component as UserControl1;
        EnableDesignMode(bc.Panel, "MyPanel");
    }
}

Solution

  • Yes I can reproduce your issue now, that is because the panel is inside usercontrol, they are added as a whole to the Form, that means the location of the panel is relative to usercontrol, so if you set the location of the panel is (x, y), then when you reopen the form, the actual location of the panel will be (usercontrol.location.X+x, usercontrol.location.Y+y).

    You can find there is not any problem if you set the location of the usercontrol in the form is (0, 0), please have a try.

    If you do not want to set the location of the usercontrol is (0, 0), as an alternative solution, you can add the following code in Form_Load event, so the location will be where you set it when you run the form:

    private void Form1_Load(object sender, EventArgs e)
    {
        this.userControl11.Panel.Location = new Point(userControl11.Panel.Location.X - userControl11.Location.X, userControl11.Panel.Location.Y - userControl11.Location.Y);
    }