views:

474

answers:

2

I want to have ONE instance of an image list that I want to share over all the forms in my application(s) (icons for the toolbar). I've seen the question asked before and people came up with a user control (which is no good, since it will create multiple instances of the imagelist and thus create unnecessary objects and overhead).

Design time support would be good, but not very essential.

In Delphi this was pretty easy: create a DataForm, share the images and you are off.

Is there a C#/.Net/Winforms variantion on that?

+2  A: 

You could simply make a static class hold an ImageList instance, and use that in your application, I guess:

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; }
}

Then you can load images from the hosted ImageList:

someControl.Image = ImageListWrapper.ImageList.Images["some_image"];

No design time support in that solution though.

Fredrik Mörk
+1  A: 

you can use a singleton class like so (see below). Which you can use the designer to populate the image list and then bind to what ever image list your using manually.


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;
    }
}
Hath