开发者

Creating a dynamic UI in winforms

开发者 https://www.devze.com 2023-04-12 19:36 出处:网络
If I want to create a winform with dynamic UI controls appearing, what\'s the best way to do that? I have a form with a textbox, a button1 to the right of it, a listbox underneath, and a button2 unde

If I want to create a winform with dynamic UI controls appearing, what's the best way to do that?

I have a form with a textbox, a button1 to the right of it, a listbox underneath, and a button2 underneath the listbox. Pressing button1 should generate another textbox underneath the first textbox and the listbox/button2 should be shifted down. If anyone's used Adobe Bridge before, the batch rename window is an example of what I'm talking about.

I was thinking of simply adding textboxN.Height to this.Size, then textboxN.Height to each of the controls (except the first textbox) Y position so they all get shifted down by text开发者_运维知识库boxN.Height pixels. But I think there's a better way of doing this. Rather, is Winforms suitable for something like this?


You -could- just add the height of the TextBox to the form's size, but tbh it would be better to use a constant that dictates the size of the TextBoxes, and then add that.

For moving the listBox/button2, anchor them to the bottom of the form, and they'll automatically stay at the same distance from the bottom of the form.

As for dynamic generation, use a List (or a Stack, depending on what exactly you're doing with it).

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

That should work. The thing with the method here is pretty much all of the placement customisation can be done with the constant values.

Is it best to do it in WinForms? Well, there's certainly no real reason to not do it in WinForms, this functionality is easy enough to implement. I'm a WPF guy myself but this is still legit.

Edited for logic errors

0

精彩评论

暂无评论...
验证码 换一张
取 消