首页 > 解决方案 > 使用字符串作为名称来控制/使用 ImageList,例如按钮和 picbox 等:this.Controls[string]

问题描述

我需要帮助使用 ImageLists。我在网上搜索了很长时间以寻找解决方案,但没有人问这个确切的问题。因此,我想使用字符串按名称访问 ImageList。

像这样:

string PicBoxName;
string ImageListName;
int ImageIndex;

private void FunctionName()
{
    this.Controls[PicBoxName].BackgroundImage = this.Controls[ImageListName].Images.[ImageIndex];
}

但这给了我一个错误,说 .Images 不存在,所以...我知道我做错了,不是 this.Controls 我需要使用...但是我该怎么办?

提前谢谢。

标签: c#winformsimagelist

解决方案


您的问题很可能是您没有将任何图像添加到ImageList. 请注意,当您调用该.Images属性时,如果该属性尚未初始化,则ImageList该类将实例化该属性。Images这意味着您可以拥有一个 nullImages属性,并且该ImageList.Images调用可以正常工作。

评论

如果尚未创建图像集合,则在您检索此属性时会创建它。

(来自https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.imagelist.images?view=netframework-4.8#System_Windows_Forms_ImageList_Images

因此,Images 属性可能尚未初始化,但如果您从设计器中添加此属性,则这些问题会在它到达您的代码之前得到处理。

您最可能的解决方案是您需要Images先将图像添加到属性中:

private void FunctionName()
{
    // From the above link:
    // Set the ImageSize property to a larger size 
    // (the default is 16 x 16).
    this.Controls[ImageListName].ImageSize = new Size(112, 112);
    this.Controls[ImageListName].Images.Add(
        Image.FromFile("path/to/image"));
    
    // now there's at least one image
    // so we can call index = 0
    this.Controls[PicBoxName].BackgroundImage = this.Controls[ImageListName].Images[0];
}

(为清楚起见进行了编辑)


推荐阅读