我使用Windows窗体。我希望DisplayMember与基类相同? 我有课
public class MyViewModel
{
public int Id { get; set; }
public Type Type { get; set; }
}
我想,我的comboBox显示Type.Name。
List<MyViewModel> list = new List<MyViewModel>();
list.Add(new MyViewModel(){ Id = 1, Type.GetType(int)});
list.Add(new MyViewModel(){ Id = 2, Type.GetType(string)});
//how i must to config displayMember???
myComboBox.DisplayMember = "Type.Name";
myComboBox.ValueMember = "Id";
myComboBox.DataSoutce = list;
但是我无法在comboBox中显示Type.Name。你能救我吗?
答案 0 :(得分:6)
ComboBox
有一个名为Format
的事件:
myComboBox.DisplayMember = "Type";//Notice this
myComboBox.Format += (s,e) => {
e.Value = ((Type)e.Value).Name;
};
答案 1 :(得分:1)
您必须创建一个具有两个属性的新类:
class MyViewModel
{
public string TypeName {get; set; }
public string Id {get; set; }
}
// generate the datasource list.
List<MyViewModel> list = new List<MyViewModel>();
list.Add(new MyViewModel(){ Id = 1, TypeName = typeof(int).Name});
list.Add(new MyViewModel(){ Id = 2, TypeName = typeof(string).Name});
// how i must to config displayMember
myComboBox.DisplayMember = "TypeName";
myComboBox.ValueMember = "Id";
myComboBox.DataSoutce = list;