组合框中基类的DisplayMember属性

时间:2013-08-29 13:37:56

标签: c# .net combobox

我使用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。你能救我吗?

2 个答案:

答案 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;