将多个列表项添加到组合框

时间:2016-05-24 12:34:11

标签: c# wpf list combobox

如何将ListForTesting中的所有testName都放入组合框中?我尝试过使用combobox_testType.ItemsSource = ListForTesting.testName,但它不起作用。

public class ManoeuvresID
{
    public string manName { get; set; }
    public int manID { get; set; }
}

public class TestID
{
    public string testName { get; set; }
    public int ID { get; set; }
    public IList<ManoeuvresID> manoeuvres { get; set; }
}

    HardCodedDatabase.TestID TestObjet = new HardCodedDatabase.TestID();
    TestObjet.manoeuvres = new List<HardCodedDatabase.ManoeuvresID>();
    HardCodedDatabase.ManoeuvresID man = new HardCodedDatabase.ManoeuvresID();
    man.manName="man1";
    man.manID = 2;
    TestObjet.manoeuvres.Add(man);
    List<HardCodedDatabase.TestID> ListForTesting = new List<HardCodedDatabase.TestID>();
    TestObjet.testName = "Steady State";
    ListForTesting.Add(TestObjet);
    TestObjet = new HardCodedDatabase.TestID();
    TestObjet.testName = "test2";
    ListForTesting.Add(TestObjet);
    combobox_testType.ItemsSource = ListForTesting;

2 个答案:

答案 0 :(得分:2)

您只需使用Items.Add或Items.AddRange添加对象项 以下示例

        foreach (var item in ListForTesting)
            comBox.Items.Add(item);

添加范围

 comBox.Items.AddRange(ListForTesting);

然后设置,您的类对象中的哪些属性将用于显示并且是您的键

        comBox.DisplayMember = "testName";
        comBox.ValueMember = "TestId";

答案 1 :(得分:1)

你试过linq

吗?
combobox_testType.ItemsSource = ListForTesting.Select(t=>t.testName);

另一种选择是使用DisplayMemberPath

combobox_testType.ItemsSource = ListForTesting;
combobox_testType.DisplayMemberPath= "testName";