ListBox toBind Dictionary <string,object =“”> </string,>

时间:2015-02-12 05:06:39

标签: c# winforms dictionary listbox bind

有没有办法将字典绑定到ListBox? 例如: 我有这个课程:

   class Person
    {
        private string _firstName;
        private string _lastName;
        private int _age;

        public Person(string firstName, string lastName, int age)
        {
            this._firstName = firstName;
            this._lastName = lastName;
            this._age = age;
        }

        public string FirstName
        {
            get { return _firstName; }
            set { this._firstName = value; }
        }

        public string LastName
        {
            get { return _lastName; }
            set { this._lastName = value; }
        }

        public int Age
        {
            get { return _age; }
            set { this._age = value; }
        }
    }

我将它用作词典的值:

private Dictionary<string, Person> _persons = new Dictionary<string, Person>();

我希望将它绑定到listBox ...但我需要选择要绑定的项目... 例如:我想绑定Person,然后所有Person只出现在listBox的DisplayMember中......

我试过这个答案: 克里斯stackoverflow.com/questions/854953/datagridview-bound-to-a-dictionary 但列表框perItem上显示的输出类似于:

{ Key = key, Value = ObjectValue }

问题:还有其他办法吗?或者如何修复此至少编辑列表框的项目?

更新 我刚刚看到这个答案: stackoverflow.com/questions/1506987/how-to-bind-dictionary-to-listbox-in-winforms

似乎有效!但我现在的问题是如果我想显示来自值的数据 ... 将什么放在listBox.DisplayMember上?

1 个答案:

答案 0 :(得分:1)

没有办法指定类似&#34; Person.FirstName&#34;在winforms的列表框的DisplayMember中。

您可以做的是覆盖Person的{​​{1}}方法,或者不是绑定您可以绑定ToString的字典......

或者只有一个类用于绑定和绑定List<Person>

List<CustomPerson>

然后将public class CustomPerson { public string Key { get; set; } public Person Person { get; set; } public string DisplayValue { get { return Person.FirstName; } } } 设为DisplayMember