簡體   English   中英

在.Net Winforms應用程序中共享圖像列表

[英]Share imagelist in .Net Winforms application

我想要一個圖像列表實例,我想在我的應用程序(工具欄的圖標)中的所有表單上共享。 我已經看過之前提出的問題,人們提出了一個用戶控件(這不好,因為它將創建imagelist的多個實例,從而創建不必要的對象和開銷)。

設計時間支持會很好,但不是很重要。

在Delphi中,這非常簡單:創建一個DataForm,共享圖像,然后您就可以離開了。

是否有C#/。Net / Winforms變體?

您可以簡單地使一個靜態類容納一個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"];

但是,該解決方案中沒有設計時間支持。

您可以像這樣使用單例類(請參見下文)。 您可以使用設計器來填充圖像列表,然后將其綁定到您手動使用的圖像列表。


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM