设计器弄乱了启用设计的自定义 UserControl 子容器的位置和大小

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

当我将此控件放到窗体上时,更改它的大小和位置,保存并关闭窗体。打开后位置和大小不一样,但是在“.Designer.cs”里面就是我设置的。 我找不到解决这个问题的方法,甚至没有人提到它。

这是我正在使用的自定义控件的一个简单示例:

[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");
    }
}

是的,我现在可以重现你的问题,那是因为面板在用户控件中,它们是作为一个整体添加到表单中的,这意味着面板的位置是相对于用户控件的,所以如果你设置位置面板的位置是(x, y),那么当你重新打开窗体时,面板的实际位置将是(usercontrol.location.X+x, usercontrol.location.Y+y).

你发现如果你把窗体中usercontrol的位置设置为(0, 0)是没有问题的,请试一试。

如果不想设置usercontrol的location为(0, 0),作为替代方案,可以在Form_Load事件中添加如下代码,这样location就会是你所在的位置当你 运行 形式时设置它:

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);
}