动态添加按钮

本文关键字:按钮 添加 动态 | 更新日期: 2023-09-27 18:22:11

我正在创建一个表单,加载时它会从我的资源文件夹中获取所有图像,并为每个文件创建一个新按钮,将按钮背景图像设置为该图像,并将该按钮添加到表单中,但它只显示1个按钮,资源文件夹中有36个文件。

我的代码如下:

ResourceSet resourceSet = Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
    object resource = entry.Value;
    Button b = new Button();
    b.BackgroundImage = (Image)resource;
    b.BackgroundImageLayout = ImageLayout.Stretch;
    b.Height = 64;
    b.Width = 64;
    this.Controls.Add(b);
}

请协助我做错事。

动态添加按钮

我的猜测是,代码确实添加了所有按钮,但它们都在一起。每个按钮将具有LeftTop的默认值,并且这些默认值对于每个按钮都是相同的。由于所有按钮都具有相同的大小,因此只有顶部按钮可见。

通过设置每个按钮的LeftTop属性来解决此问题。显然,对于LeftTop,每个不同的按钮需要具有不同的值。


要回答您在评论中提出的问题,您可以使用以下代码:

const int buttonSize = 64;
int left = 0;
int top = 0;
foreach (DictionaryEntry entry in resourceSet)
{
    object resource = entry.Value;
    Button b = new Button();
    b.BackgroundImage = (Image)resource;
    b.BackgroundImageLayout = ImageLayout.Stretch;
    b.Bounds = Rectangle(left, top, buttonSize, buttonSize);
    this.Controls.Add(b);
    // prepare for next iteration
    left += buttonSize;
    if (left+buttonSize>this.ClientSize.Width)
    {
        left = 0;
        top += 64;
    }
}