(注:我標記它winforms
但我認爲它適用於WPF以及)是否可以將模型類的屬性綁定到ComboBox?
我有一個組合框和一個模型類(比方說人)。 Person包含多個公共屬性(名稱,年齡,性別,地址等)。
是否有一種(標準)方式將我的ComboBox的數據源綁定到這些屬性,所以ComboBox顯示「Name」,「Age」,「Sex」和「Adress」作爲它的列表?
(注:我標記它winforms
但我認爲它適用於WPF以及)是否可以將模型類的屬性綁定到ComboBox?
我有一個組合框和一個模型類(比方說人)。 Person包含多個公共屬性(名稱,年齡,性別,地址等)。
是否有一種(標準)方式將我的ComboBox的數據源綁定到這些屬性,所以ComboBox顯示「Name」,「Age」,「Sex」和「Adress」作爲它的列表?
您的形式:
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; }
}
我知道這將不得不處理悲傷的反思......但這是我所需要的,謝謝。 – Kilazur 2014-11-25 13:04:06
要獲得的屬性名稱,使用反射:
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
)。
在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}"/>
HTTP://stackoverflow.c om/questions/1091414/winforms-combobox-with-multiple-columns-c – Sajeetharan 2014-11-25 12:08:13
是否要在組合框中顯示屬性名稱? – Dennis 2014-11-25 12:11:25
是的,那是我的目標。 @Sajeetharan:無關。 – Kilazur 2014-11-25 12:26:10