动态添加按钮

joh*_*nie 0 c# forms

我正在创建一个表单,并在加载时从我的资源文件夹中获取所有图像,并为每个文件创建一个新按钮,将按钮背景图像设置为该图像并将该按钮添加到表单,但它只显示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);
}
Run Code Online (Sandbox Code Playgroud)

请帮助我做错了什么.

Dav*_*nan 5

我的猜测是代码确实添加了所有按钮,但它们都是彼此重叠的.每个按钮都有一个默认值,Left并且每个按钮的Top默认值都相同.由于按钮都具有相同的尺寸,因此只有顶部按钮可见.

通过设置每个按钮的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;
    }
}
Run Code Online (Sandbox Code Playgroud)