如何在列表框中显示替代对象的表示?

Yod*_*oda 2 c# listbox winforms

前段时间我遇到过一篇文章,其中作者指出,如果我有一个,ListBox其中的对象不必由该内部的方法string返回来表示ToString()ListBox

这怎么可能?

例如我有一个:

 public class Car {
        public static int ID { get; set; }
        public int Id { get; set; }
        public string Make { get; set; }
        public int Power { get; set; }


        public Car(string Make, int Power) {
            Id = ID++;
            this.Make = Make;
            this.Power = Power;
            AddToClassExtension(this);
        }


        public override string ToString() {
            return Id + "." + Make + " " + Power;
        }
}
Run Code Online (Sandbox Code Playgroud)

ListBox lba 中的a Form。我想只car.Id在每一行显示lb但不改变ToString()方法。是否可以?

Jon*_*eet 5

您可以指定DisplayMember-ListBox在本例中,您将其设置"Id"为以便控件从显示的每个项目中获取该属性。

这是一个简短但完整的示例(为简洁起见,使用 C# 6):

using System;
using System.Collections.Generic;
using System.Windows.Forms;

public class Car {
    // C# 6 finally allows read-only autoprops. Yay!
    public int Id { get; }
    public string Make { get; set; }

    public Car(int id, string make)
    {
        this.Id = id;
        this.Make = make;
    }

    public override string ToString() {
        return Id + "." + Make;
    }
}

class Test
{
    static void Main()
    {
        var cars = new List<Car>
        {
            new Car(10, "Ford"),
            new Car(20, "Nissan"),
            new Car(45, "Rolls-Royce")
        };

        var listBox = new ListBox
        {
            DataSource = cars,
            DisplayMember = "Id",
            Dock = DockStyle.Fill
        };

        var form = new Form
        { 
            Controls = { listBox }
        };
        Application.Run(form);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于更复杂的格式化,您可以Format在启用格式化后使用该事件。例如,在上面的示例中,将listBox声明更改为:

var listBox = new ListBox
{
    DataSource = cars,
    Dock = DockStyle.Fill,
    FormattingEnabled = true,
};
listBox.Format += (sender, args) =>
{
    var car = (Car) args.Value;
    args.Value = string.Format("Id: {0}; Make: {1}", car.Id, car.Make);
};
Run Code Online (Sandbox Code Playgroud)