如何在 C# ListBox 中截断 DisplayMember?
how to truncate DisplayMember in C# ListBox?
我有一个显示完整文件路径列表的 winforms ListBox。但如您所见,Path
属性 太长了。如何让 ListBox 仅显示文件名而不显示完整路径而不向列表条目添加全新的 属性?
myListBox.DisplayMember = "Path";
如果您将文件路径转换为 System.IO.FileInfo 对象,它应该会给您更多选择。
试试这个:
string[] files = System.IO.Directory.GetFiles("C:\tmp");
List<System.IO.FileInfo> fiList = new List<System.IO.FileInfo>();
foreach(string f in files)
fiList.Add(new System.IO.FileInfo(f));
myListBox.DataSource = fiList;
myListBox.DisplayMember = "Name";
myListBox.ValueMember = "FullName";
无需向列表条目添加全新的 属性,您可以使用列表框的 DrawItem 事件(确保将 DrawMode 属性 更改为 OwnerDrawFixed)。
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.Graphics.DrawString(System.IO.Path.GetFileName(lst[e.Index].DisplayValue), e.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
e.DrawFocusRectangle();
}
我有一个显示完整文件路径列表的 winforms ListBox。但如您所见,Path
属性 太长了。如何让 ListBox 仅显示文件名而不显示完整路径而不向列表条目添加全新的 属性?
myListBox.DisplayMember = "Path";
如果您将文件路径转换为 System.IO.FileInfo 对象,它应该会给您更多选择。
试试这个:
string[] files = System.IO.Directory.GetFiles("C:\tmp");
List<System.IO.FileInfo> fiList = new List<System.IO.FileInfo>();
foreach(string f in files)
fiList.Add(new System.IO.FileInfo(f));
myListBox.DataSource = fiList;
myListBox.DisplayMember = "Name";
myListBox.ValueMember = "FullName";
无需向列表条目添加全新的 属性,您可以使用列表框的 DrawItem 事件(确保将 DrawMode 属性 更改为 OwnerDrawFixed)。
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.Graphics.DrawString(System.IO.Path.GetFileName(lst[e.Index].DisplayValue), e.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
e.DrawFocusRectangle();
}