如何使用SortedList填充组合框

时间:2017-01-03 21:24:47

标签: c# wpf combobox sortedlist

我自己创建了一个SortedList,我无法绑定到组合框,我不是从XAML那里做的,我是从代码中做到的:

 SortedList<int, string> AreaList = new SortedList<int, string>();
            AreaList.Add(1, "Agriculture");
            AreaList.Add(2, "Forestry");
            AreaList.Add(3, "Fruits");
            AreaList.Add(4, "Food");
            AreaList.Add(5, "Metals");
            AreaList.Add(6, "Mining");
            AreaList.Add(7, "Electricity");
            AreaList.Add(8, "Building Contracts");
            AreaList.Add(9, "Transport");
            AreaList.Add(10, "Alcohol");
            AreaList.Add(11, "Information Technologies");
            AreaList.Add(12, "Health And Social Services");
            AreaList.Add(13, "Art and Entertainement");
            AreaList.Add(14, "Hospitality Business");
            AreaList.Add(15, "Education");
            AreaList.Add(16, "Real Estate");
            AreaList.Add(17, "Sales");
            AreaList.Add(18, "Architecture");
            AreaList.Add(19, "Engineering");
            AreaList.Add(20, "Wholesale");

        comboBox1.ItemsSource = AreaList.ToList();
        comboBox1.SelectedValue = "TKey";
        comboBox1.DisplayMemberPath = "TValue";

我不知道我做错了什么,这是我第一次使用SortedLists,而且我是WPF的初学者。

1 个答案:

答案 0 :(得分:1)

不确定为什么需要SortedList,但最后(由于ToList()调用)您实际上绑定到List<KeyValuePair<int, string>>,因此您需要设置SelectedValuePathDisplayMemberPath如下:

comboBox1.SelectedValuePath = "Key"; // bind to KeyValuePair<int, string>.Key property
comboBox1.DisplayMemberPath = "Value";  // bind to KeyValuePair<int, string>.Value property