c# - 使用字符串作为名称来控制/使用 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 我需要使用...但是我该怎么办?
提前谢谢。
解决方案
您的问题很可能是您没有将任何图像添加到ImageList
. 请注意,当您调用该.Images
属性时,如果该属性尚未初始化,则ImageList
该类将实例化该属性。Images
这意味着您可以拥有一个 nullImages
属性,并且该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];
}
(为清楚起见进行了编辑)
推荐阅读
- valgrind - Kotlin/Native,当 valgrind 转储核心时内存泄漏搜索
- powershell - 遍历锯齿状数组
- c++ - 在 C++ 中创建一个全局对象数组
- c++ - 现代 C++ 中的贝塞尔曲线
- c# - Castle ActiveProject 从 FindAllByProperty 检索陈旧数据
- ebay-api - eBay API:getMostWatchedItems 返回 RequestError
- javascript - OctoberCMS Javascript API AJAX 调用组件函数以更新组件的部分
- python - 如何使用 pyparsing 定义句子的语法
- pyspark - 从 .egg 而不是 .py 运行 PySpark 作业
- fastlane - 无法使用 Ruby 测试 Fastlane 中的目录是否已存在