【问题标题】:how to truncate DisplayMember in C# ListBox?如何在 C# ListBox 中截断 DisplayMember?
【发布时间】:2018-06-20 13:50:37
【问题描述】:

我有一个显示完整文件路径列表的 winforms ListBox。但正如您所见,Path 属性太长了。如何在不向列表条目添加全新属性的情况下让 ListBox 仅显示文件名而不显示完整路径?

myListBox.DisplayMember = "Path";

【问题讨论】:

    标签: c# text listbox truncate


    【解决方案1】:

    如果您将文件路径转换为 ​​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";
    

    【讨论】:

      【解决方案2】:

      无需向列表条目添加全新的属性,您就可以使用列表框的 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();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-26
        • 2011-09-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多