由ListBox控件自动管理的泛型对象

本文关键字:泛型 对象 管理 ListBox 控件 | 更新日期: 2023-09-27 18:26:17

我看到的使用ListBox控件的所有示例都使用string数据或List<string>数据源。

如果新类要用作WinForms ListBox控件的数据源,那么它的基本要求是什么?

由ListBox控件自动管理的泛型对象

就我个人而言,我会按照ListBoxItem<T>,然后ListBoxItem看起来像这样:

public class ListBoxItem<T>
{
    private Func<T, string> _getText;
    public T Item { get; private set; }
    public ListBoxItem<T>(T item, Func<T, string> getText)
    {
        Item = item;
        _getText = getText;
    }
    public override string ToString()
    {
        return _getText(Item);
    }
}

然后,每当ListBoxItem显示在ListBox视图中时,框架本身就会调用ToString,并且您已经指定了它应该如何显示。

希望这能澄清问题。