如果我想创建一个显示动态 UI 控件的 winform,最好的方法是什么?
我有一个带有文本框的表单,其右侧有一个按钮 1,下方有一个列表框,列表框下方有一个按钮 2。按下 button1 应该在第一个文本框下方生成另一个文本框,并且列表框/button2 应该向下移动。如果有人以前使用过 Adobe Bridge,批量重命名窗口就是我所说的一个例子。
我想简单地将 textboxN.Height
添加到 this.Size
,然后将 textboxN.Height
添加到每个控件(除了第一个文本框)Y 位置,因此它们都向下移动 textboxN.Height
像素。但我认为有更好的方法来做到这一点。相反,Winforms 适合这样的事情吗?
最佳答案
您 - 可以 - 只将 TextBox 的高度添加到窗体的大小,但老实说,最好使用一个常量来指示 TextBox 的大小,然后添加它。
要移动 listBox/button2,将它们锚定到表单底部,它们将自动与表单底部保持相同的距离。
至于动态生成,使用列表(或堆栈,具体取决于您使用它做什么)。
partial class Form1 : Form
{
List<TextBox> textBoxes = new List<TextBox>(); // or stack
const int textBoxWidth = 200; // control variables for TextBox placement
const int textBoxHeight = 50;
const int textBoxMargin = 5;
void button1_Click(object sender, EventArgs e)
{
this.Height += textBoxHeight + textBoxMargin;
TextBox tb = new TextBox();
if (textBoxes.Count == 0)
{
tb.Top = textBoxMargin;
}
else
{
tb.Top = ((textBoxHeight + textBoxMargin) * textBoxes.Count) + textBoxMargin;
}
tb.Left = textBoxMargin;
tb.Height = textBoxHeight;
tb.Width = textBoxWidth;
textBoxes.Add(tb);
this.Controls.Add(tb);
}
}
那应该行得通。此处方法的特点是几乎所有放置自定义都可以使用常量值完成。
在 WinForms 中最好吗?好吧,当然没有真正的理由不在 WinForms 中这样做,这个功能很容易实现。我自己是一个 WPF 人,但这仍然是合法的。
因逻辑错误而编辑
关于c# - 在 winforms 中创建动态 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7765855/