我有一个列表框,显示一组引用文本文件的文件名。我认为显示完整路径在美学上没有吸引力,所以我使用 Path.GetFileName
来截断目录部分。
但是现在,当用户选择要打开的特定文件名时,我丢失了路径。这些文件可以位于本地计算机上的任何位置(目前)。
如何使用列表框来显示漂亮的文件名,同时也引用实际文件?
编辑:我喜欢为每个列表框项目自定义包装类的想法。
最佳答案
我过去所做的是为我想在 ListBox 中显示的对象创建一个包装类。在这个类中覆盖 ToString
到您要在列表框中显示的字符串。
当您需要获取所选项目的详细信息时,将其转换为包装类并拉取您需要的数据。
这是一个丑陋的例子:
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 组件并添加一个 MouseMove
ListBox 的事件处理程序以检索 FileFullname
FileLIstBoxItem
的属性值用户将鼠标悬停在上面。
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 中的工具提示(接受的答案,代码重新格式化为我喜欢的风格)。
关于c# - 生成了文件名列表,但没有文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873924/