【问题标题】:How To fill a combobox with SortedList如何用 SortedList 填充组合框
【发布时间】:2017-01-03 21:24:46
【问题描述】:

我自己创建了一个 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 的初学者。

【问题讨论】:

    标签: c# wpf combobox sortedlist


    【解决方案1】:

    不知道为什么你需要SortedList,但最后(由于ToList()调用)你实际上绑定到List&lt;KeyValuePair&lt;int, string&gt;&gt;,所以你需要设置SelectedValuePathDisplayMemberPath如下:

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

    【讨论】:

    • 我应该只使用常规列表吗?有了这个,它仍然给了我一个 System.NullReferenceException! @IvanStoev
    • 我不知道是什么给了你NullReferenceException。当我将您提供的代码与我的更正一起放入时,我得到了一个填充的组合框。
    • 我终于弄明白了,我删除了 InitializeComponent();这就是它给我例外的原因!所以你是对的! @IvanStoev
    猜你喜欢
    • 2015-06-16
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2011-11-20
    • 2011-12-12
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多