The Framework doesn't have any mechanism to handle resources like this as far as ensuring that you don't end up with duplicates loaded. This is particularly true in the case of a TreeView since the ImageList it uses maintains those images as resources local to the form which contains the TreeView.
An approach I have used in the past is to create a singleton object that wraps an ImageList. This allows you to control when/how an image gets added to the ImageList.
public sealed class ImageListManager
{
private static volatile ImageListManager instance;
private static object syncRoot = new object();
private ImageList imageList;
private ImageListManager()
{
this.imageList = new ImageList();
this.imageList.ColorDepth = ColorDepth.Depth32Bit;
this.imageList.TransparentColor = Color.Magenta;
}
/// <summary>
/// Gets the <see cref="System.Windows.Forms.ImageList"/>.
/// </summary>
public ImageList ImageList
{
get
{
return this.imageList;
}
}
/// <summary>
/// Adds an image with the specified key to the end of the collection if it
/// doesn't already exist.
/// </summary>
public void AddImage(string imageKey, Image image)
{
if (!this.imageList.ContainsKey(imageKey))
{
this.imageList.Add(imageKey, image);
}
}
/// <summary>
/// Gets the current instance of the
/// <see cref="ImageListManager"/>.
/// </summary>
public static ImageListManager Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new ImageListManager();
}
}
}
return instance;
}
}
}
You then give the TreeView a reference to that ImageList, generally done in the forms constructor after the call to InitializeComponent()
.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.treeView1.ImageList = ImageListManager.Instance.ImageList;
}
// Making some guesses about how you are adding nodes
// and getting the associated image.
public void AddNewTreeNode(string text, string imageKey, Image image)
{
TreeNode node = new TreeNode("display text");
node.Name = "uniqueName";
// This tells the new node to use the image in the TreeView.ImageList
// that has imageKey as its key.
node.ImageKey = imageKey;
node.SelectedImageKey = imageKey;
this.treeView1.Nodes.Add(node);
// If the image doesn't already exist, this will add it.
ImageListManager.Instance.AddImage(imageKey, image);
}
}