使用C#编程中在TreeView和ListView中添加图标有很简便的方法。
采用了TreeView的ImageList属性,将一个初始化好的ImageList赋值给TreeView,通过选中ImageList中的下标就可以将图片赋给Nodes。
private void InitImageList()
{
imageList = new ImageList();
imageList.ImageSize = new Size(16, 16);
imageList.ColorDepth = ColorDepth.Depth32Bit;
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(Application.StartupPath + @"../../../Resources/32x32PNG");
foreach (System.IO.FileInfo file in directory.GetFiles("*.png"))
{
imageList.Images.Add(file.Name, Image.FromFile(file.FullName) );
}
}
public void SetTreeView()
{
treeViewFiles.Nodes.Clear();
treeViewFiles.ImageList = imageList;
TreeNode fileNode = treeViewFiles.Nodes.Add("Nodes:");
TreeNode child = fileNode.Nodes.Add(null, fileName, 4);
child.ToolTipText = file;
child.ImageIndex = 8;
child.ContextMenuStrip = this.contextMenuStripEditFile;
}