我想要一个图像列表的实例,我希望在我的应用程序中的所有表单(工具栏的图标)上共享。我已经看过之前提出的问题,人们想出了一个用户控件(这不好,因为它会创建图像列表的多个实例,从而产生不必要的对象和开销)。
设计时间支持很好,但不是很重要。
在Delphi中,这非常简单:创建一个DataForm,共享图像,然后就可以了。
是否有C#/。Net / Winforms变体?
答案 0 :(得分:5)
你可以简单地让一个静态类持有一个ImageList实例,并在你的应用程序中使用它,我猜:
public static class ImageListWrapper
{
static ImageListWrapper()
{
ImageList = new ImageList();
LoadImages(ImageList);
}
private static void LoadImages(ImageList imageList)
{
// load images into the list
}
public static ImageList ImageList { get; private set; }
}
然后您可以从托管的ImageList加载图像:
someControl.Image = ImageListWrapper.ImageList.Images["some_image"];
但该解决方案中没有设计时支持。
答案 1 :(得分:3)
你可以使用像这样的单例类(见下文)。您可以使用设计器填充图像列表,然后绑定到您手动使用的图像列表。
using System.Windows.Forms;
using System.ComponentModel;
//use like this.ImageList = StaticImageList.Instance.GlobalImageList
//can use designer on this class but wouldn't want to drop it onto a design surface
[ToolboxItem(false)]
public class StaticImageList : Component
{
private ImageList globalImageList;
public ImageList GlobalImageList
{
get
{
return globalImageList;
}
set
{
globalImageList = value;
}
}
private IContainer components;
private static StaticImageList _instance;
public static StaticImageList Instance
{
get
{
if (_instance == null) _instance = new StaticImageList();
return _instance;
}
}
private StaticImageList ()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.globalImageList = new System.Windows.Forms.ImageList(this.components);
//
// GlobalImageList
//
this.globalImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.globalImageList.ImageSize = new System.Drawing.Size(16, 16);
this.globalImageList.TransparentColor = System.Drawing.Color.Transparent;
}
}