添加“标签"属性到 ListBox 的项目,如 TreeView 的节点? [英] Adding a "Tag" property to a ListBox's items, like a TreeView's Nodes?

查看:10
本文介绍了添加“标签"属性到 ListBox 的项目,如 TreeView 的节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个 Windows 窗体项目,该项目将在空闲时间搜索指定文件夹中的文件.到目前为止,我的 TreeView 就像在 Windows 资源管理器中一样显示文件夹.

I'm making a Windows Form project that will search for files in the specified folders in my spare time. So far, I've got my TreeView that displays folders just like in the Windows Explorer.

我还有一个 ListBox 可以存储所有搜索结果.当我双击该列表中的一个项目时,我希望可以选择打开文件.

I also have a ListBox that will store all the search results. When I double click an item in that list, I want to have the option of opening the file.

到目前为止,我看到了三种方法:

So far, I see three ways of doing this:

  1. 让 ListBox 显示完整路径.
  2. 使用全局列表或数组来跟踪完整路径,而列表框仅显示文件名.然后使用索引来匹配对应的item.
  3. 为我的每个 ListBox 项目添加一个Tag"属性,就像 TreeView 的节点一样.

对我来说,第三种方法是最吸引人的,但我不知道从哪里开始.到目前为止,我一直在摆弄一个控件库,但无济于事.

To me, the third method is the most appealing, but I have no idea where to start. Up until now, I've been fiddling with a Control Library to no avail.

我希望能够让标签以与 TreeView 类似的方式工作.因此,检索标签和设置标签的代码看起来像 ListBox1.Items[i].Tag 或者可能是 ListBox1.Tag[i] 如果前者不是可能.

I was hoping to be able to get the Tag to work in a similar fashion as with the TreeView. So, the code to retrieve the tag and set the tag would look like ListBox1.Items[i].Tag or maybe ListBox1.Tag[i] if the former is not possible.

任何帮助将不胜感激.

推荐答案

您应该创建一个自定义 SearchResult 类,该类具有返回完整路径的属性.
该类应覆盖 ToString() 并返回要在列表框中显示的文本.

You should create a custom SearchResult class with a property that returns the full path.
The class should override ToString() and return the text you want to display in the listbox.

然后您可以将您的类的实例直接放入列表框中,并将列表框中的项目投射回该类以获取属性.

You can then put instances of your class directly into the listbox, and cast an item from the listbox back to the class to get the property.

这篇关于添加“标签"属性到 ListBox 的项目,如 TreeView 的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆