我过去所做的是为我想在 ListBox 中显示的对象创建一个包装类。在此类中,将ToString 覆盖为要在 ListBox 中显示的字符串。
当您需要获取所选项目的详细信息时,将其强制转换为包装类并提取您需要的数据。
这是一个丑陋的例子:
class FileListBoxItem
{
public string FileFullname { get; set; }
public override string ToString() {
return Path.GetFileName(FileFullname);
}
}
用 FileListBoxItems 填充您的 ListBox:
listBox1.Items.Add(new FileListBoxItem { FileFullname = @"c:\TestFolder\file1.txt" })
像这样取回所选文件的全名:
var fileFullname = ((FileListBoxItem)listBox1.SelectedItem).FileFullname;
编辑
@user1154664 在对您最初的问题的评论中提出了一个很好的观点:如果显示的文件名相同,用户将如何区分两个 ListBox 项?
这里有两个选项:
同时显示每个 FileListBoxItem 的父目录
为此,请将ToString 覆盖更改为:
public override string ToString() {
var di = new DirectoryInfo(FileFullname);
return string.Format(@"...\{0}\{1}", di.Parent.Name, di.Name);
}
在工具提示中显示 FileListBoxItem 的完整路径
为此,将 ToolTip 组件拖放到表单上,并为 ListBox 添加一个 MouseMove 事件处理程序,以检索用户将鼠标悬停在 FileLIstBoxItem 上的 FileFullname 属性值。
private void listBox1_MouseMove(object sender, MouseEventArgs e) {
string caption = "";
int index = listBox1.IndexFromPoint(e.Location);
if ((index >= 0) && (index < listBox1.Items.Count)) {
caption = ((FileListBoxItem)listBox1.Items[index]).FileFullname;
}
toolTip1.SetToolTip(listBox1, caption);
}
当然,您可以将第二个选项与第一个选项一起使用。
Source 用于 ListBox 中的工具提示(已接受的答案,将代码重新格式化为我喜欢的风格)。