4

我想要一个图像列表的实例,我想在我的应用程序中的所有表单(工具栏的图标)上共享它。我已经看过之前提出的问题,人们想出了一个用户控件(这不好,因为它会创建图像列表的多个实例,从而创建不必要的对象和开销)。

设计时支持会很好,但不是很重要。

在 Delphi 中,这非常简单:创建一个 DataForm,共享图像,然后你就可以离开了。

是否有 C#/.Net/Winforms 变体?

4

2 回答 2

6

你可以简单地让一个静态类持有一个 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"];

但是,该解决方案中没有设计时支持。

于 2009-07-17T09:18:43.033 回答
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;
    }
}
于 2009-07-17T09:36:29.800 回答