我想自动调整一些生成的控件。我创建了两种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;
}
}
CustomControl:
public CustomControl(string labelCaption)
{
InitializeComponent();
Label label = new Label();
label.Text = "Rtb..." + labelCaption;
//label.Dock = DockStyle.Top;
//contentPanel.Controls.Add(label);//disabled for now
}
答案 0 :(得分: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);