【问题标题】:Is it possible to bind properties of a model class to a ComboBox?是否可以将模型类的属性绑定到 ComboBox?
【发布时间】:2015-01-23 10:22:18
【问题描述】:

(注意:我将其标记为 winforms 但我认为它也适用于 WPF)

我有一个 ComboBox 和一个模型类(比如说 Person)。 Person 包含多个公共属性(姓名、年龄、性别、地址等)。

是否有(标准)方法将我的 ComboBox 的数据源绑定到这些属性,因此 ComboBox 将“姓名”、“年龄”、“性别”和“地址”显示为列表?

【问题讨论】:

标签: c# winforms binding properties combobox


【解决方案1】:

要获取属性名称,请使用反射:

var propertyNames = person
    .GetType() // or typeof(Person)
    .GetProperties()
    .Select(p => p.Name)
    .ToArray();

(因为所有Person 实例的结果都是相同的,所以我会缓存它,例如在静态变量中)。

要在组合框中显示属性,请使用DataSource (WinForms):

comboBox.DataSource = propertyNames;

ItemsSource (WPF):

<ComboBox ItemsSource="{Binding PropertyNames}"/>

(假设当前数据上下文包含公共属性PropertyNames)。

【讨论】:

    【解决方案2】:

    您的表格:

    public partial class Form1 : Form
    {
        BindingList<PropertyInfo> DataSource = new BindingList<PropertyInfo>();
    
        public Form1()
        {
    
            InitializeComponent();
    
            comboBox1.DataSource = new BindingList<PropertyInfo>(typeof(Person).GetProperties());
            // if want to specify only name (not type-name/property-name tuple)
            comboBox.DisplayMember = "Name";
        }
    }
    

    你的班级:

    public class Person
    {
        public string Name { get; set; }
        public uint Age { get; set; }
        public bool Sex { get; set; }
        public string Adress { get; set; }
    }
    

    【讨论】:

    • 我很遗憾地知道它必须处理反射......但这正是我所需要的,谢谢。
    【解决方案3】:

    在 WPF 中:

    public class Person
    {
        public string Name { get; set; }
        public int? Age { get; set; }
        public string Sex { get; set; }
        public string Address { get;set;}
    
        public override string ToString()
        {
            return string.Format("{0}, {1}, {2}, {3}", Name, Age, Sex, Address);
        }
    }
    
    public class PersonViewModel
    {
        public PersonViewModel()
        {
            PersonList = (from p in DataContext.Person
                          select new Person
                          {
                              Name = p.Name,
                              Age = p.Age,
                              Sex = p.Sex,
                              Address = p.Address
                          }).ToList();
        }
    
        public List<Person> PersonList { get; set; }
        public Person SelectedPerson { get; set; }
    }
    

    XAML:

    <ComboBox ItemsSource="{Binding PersonList}" SelectedItem="{Binding SelectedPerson}"/>
    

    【讨论】:

    猜你喜欢
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2013-01-30
    • 2011-04-01
    • 2017-05-13
    • 2011-12-28
    相关资源
    最近更新 更多