0

我想自动调整一些生成的控件。我创建了两种TextBox类型和两种CustomControl类型,它们是UserControl. 每个CustomControl都有一个Label显示我称之为标题的字符串。我只能看到两个文本框之一。我只能看到两个标题之一。如何显示表单中的所有控件?我不喜欢自己管理控制位置。而是坚持Dock设置。

 public partial class SomeForm : Form
{
    public SomeForm()
    {
        InitializeComponent();
        LoadControls();//I can only see the first control caption and textBox2
        //how can I display both textboxes and both captions?
    }

    private void LoadControls()
    {
        TextBox textBox = GenerateTextBox("First textbox");
        TextBox textBox2 = GenerateTextBox("Second textbox");

        CustomControl control = new CustomControl(labelCaption: "First control caption");
        CustomControl control2 = new CustomControl(labelCaption: "second control caption");            

        //add the textboxes to the usercontrols
        control.Controls.Add(textBox);
        control2.Controls.Add(textBox2);            

        //this displays only 1 control (incorrect)
        flowLayoutPanel1.Controls.Add(control);
        flowLayoutPanel1.Controls.Add(control2);
        flowLayoutPanel1.SetFlowBreak(control, true);
        flowLayoutPanel1.SetFlowBreak(control2, true);

        //this displays both controls (correct)
        //flowLayoutPanel1.Controls.Add(textBox);
        //flowLayoutPanel1.Controls.Add(textBox2);
        //flowLayoutPanel1.SetFlowBreak(textBox, true);
        //flowLayoutPanel1.SetFlowBreak(textBox2, true);
    }

    private static TextBox GenerateTextBox(string text)
    {
        TextBox textBox = new TextBox();
        textBox.Text = text;
        textBox.Dock = DockStyle.Top;
        return textBox;
    }
}

自定义控件:

    public CustomControl(string labelCaption)
    {
        InitializeComponent();
        Label label = new Label();
        label.Text = "Rtb..." + labelCaption;
        //label.Dock = DockStyle.Top;
        //contentPanel.Controls.Add(label);//disabled for now
    }
4

1 回答 1

1

问题是您使用 DockStyle.Top 进行的初始化:

        CustomControl control = new CustomControl(labelCaption: "First control caption");
        control.Dock = DockStyle.Top;        
        CustomControl control2 = new CustomControl(labelCaption: "second control caption");            
        control2.Dock = DockStyle.Top;

他们会以这种方式相互叠加。不要使用 DockStyle,而是使用定位属性:

       control.Top = 0;
       control2.Top = control.Height;

这应该可以让你到达你需要去的地方。

了解如何做好这件事的一个好方法是查看设计器生成的代码。在设计器中手工完成,然后查看生成的代码,它将帮助您概括将来如何自己在代码中进行定位。

根据您的评论进行编辑:

您可以使用FlowLayoutPanel并在每个之后设置 FlowBreak:

flowLayoutPanel.Controls.Add(control);
flowLayoutPanel.Controls.Add(control2);
flowLayoutPanel.SetFlowBreak(control, true);
flowLayoutPanel.SetFlowBreak(control2, true);
于 2012-12-05T00:55:44.820 回答