开发者

CheckedListBox - Collection of FileInfo objects - Display Custom ToString

开发者 https://www.devze.com 2023-04-10 02:52 出处:网络
I have a CheckedListBox in a WinForms app (3.5 runtime), and I am adding a bunch of FileInfo objects to the Items ObjectCollection.The problem is that I don\'t like what is displayed in the CheckedLis

I have a CheckedListBox in a WinForms app (3.5 runtime), and I am adding a bunch of FileInfo objects to the Items ObjectCollection. The problem is that I don't like what is displayed in the CheckedListBox (since the FileInfo was from a Directory.GetFiles() it just shows the FileInfo.Name of the file in the listbox).

Is there any easy way to change what is d开发者_如何学Cisplayed in the CheckedListBox without having to create a seperate custom class/object.

I am basically doing

checkedListBox.Items.Add(fileInfo)

and the result is just the file name of the file.

Changing display member works but I can't create something custom, only the existing properties in the FileInfo class.

I want to be able to display something like Name - FullName

Example (desired): File1.txt - C:\Path\SubPath\File1.txt


Actually, it seems like it should be possible after all. The CheckedListBox has a FormattingEnabled property and a Format event inherited from ListBox which is called before each item is displayed. So something along these lines should work:

myCheckedListBox.FormattingEnabled = true;
myCheckedListBox.Format += (s, e) => { e.Value = string.Format("{0} - {1}", ((FileInfo)e.ListItem).Name, ((FileInfo)e.ListItem).FullName); };

Haven't tested it though. See also MSDN

Old answer:

I don't think you can do it without creating a wrapper. Although 10 lines of code don't seem all that bad to me:

class FileInfoView
{
    public FileInfo Info { get; private set; }

    public FileInfoView(FileInfo info)
    {
        Info = info;
    }

    public override string ToString()
    {
        // return whatever you want here
    }
}

The additional advantage to having a view model is that you can decorate it further for display purposes all the way you like.


I dont know if there is work around for this except creating a custom class and include an instance of FileInfo inside it and in this way you either create a new property and include a custom data in it or override the ToString() function

something like (this for demonstration purposes)

 MyFileInfo
    {
        public FileInfo TheFileInfo;
        public string CustomProperty
        {
           get
           {
               if(this.TheFileInfo != null)
                    return this.TheFileInfo.FileName + this.TheFileInfo.FullName;
                return string.Empty;
           }
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号