我想感谢先进的贡献者,我宁愿坚持这个:
我创建了一个名为listView1的列表视图,当程序运行时,它会从名为treeView1的树视图中指定的特定文件夹中显示数据文件(.txt,.doc等).在数据文件旁边的这些相同文件夹中是图标文件(.ico).我想指定.ico显示为将加载到listView1的.txt或.doc文件的图像.数据文件和图标文件都具有相同的名称,只是一个不同的扩展名.因此,我已经有了一种将图标文件与数据文件相匹配的方法.但是,我似乎无法找到一种方法以图形方式将图标文件指定为listView1中要为数据文件显示的图像.我无法使用图像列表,因为您只能根据图像索引而不是图像名称来分配图像列表中的图像.所有的迹象似乎都指向创建一个数组但我无法弄清楚如何将数组中的图像分配给数据文件,同时我将它添加到listView1.
我希望有道理,谢谢!
将图像文件添加到ImageList后,您肯定可以通过其名称(ImageKey属性)来引用它们.以下代码有效.它相当粗糙,因为我不知道你如何使用数据填充Treeview或Listview.我只是输入了一些测试数据,并使用常用方法填充Treenodes和ListViewItems.
希望这可以帮助.如果您有疑问,请告诉我...
public partial class Form1 : Form
{
// A Class member variable to hold images, to be used by both the
// TreeView AND the ListView:
ImageList _myImagelist;
public Form1()
{
InitializeComponent();
// Initialize your memeber variable:
_myImagelist = new ImageList();
// Add some hokey test images for this arbitrary example:
_myImagelist.Images.Add("Image1", Properties.Resources.SomeImage);
_myImagelist.Images.Add("Image2", Properties.Resources.AnotherImage);
// Some crude code to populate the list with test data:
TreeView lst = this.treeView1;
lst.ShowPlusMinus = true;
// Set a reference to your member variable:
lst.ImageList = _myImagelist;
// Now populate your tree nodes and subnodes:
TreeNode parent;
//A parent . . .
parent = lst.Nodes.Add("FirstNode", "Image One", "Image1");
// . . . with children:
parent.Nodes.Add("P1:S1", "Parent One Child One", "Image1");
parent.Nodes.Add("P1:S2", "Parent One Child Two", "Image1");
// Another parent . . .
parent = lst.Nodes.Add("SecondNode", "Image Two", "Image2");
// . . . More children:
parent.Nodes.Add("P2:S1", "Parent Two Child One", "Image2");
parent.Nodes.Add("P2:S2", "Parent Two Child Two", "Image2");
}
// Event handler for the AfterSelect Event:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
TreeNode nd = e.Node;
this.FillList(nd);
}
private void FillList(TreeNode node)
{
ListView lv = this.listView1;
lv.View = View.List;
// Set the reference to your same member variable:
lv.SmallImageList = _myImagelist;
lv.Items.Clear();
foreach (TreeNode nd in node.Nodes)
{
// The Listview also has an override of the .Add method which accepts the image KEY as
// an argument. The nd.ImageKey property returns a string, which the ListView item recognizes
// as the key for an item in the referenced ImageList:
ListViewItem newItem = new ListViewItem(nd.Text, nd.ImageKey);
lv.Items.Add(nd.Name, nd.Text, nd.ImageKey);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4192 次 |
| 最近记录: |