你可以通过自己的
Items
属性将原始
ItemsCollection
作为参数,来隐藏
Items
属性。
测试示例类:
public class Order
{
public Int32 ID { get; set; }
public string Reference { get; set; }
public Order() { }
public Order(Int32 inID, string inReference)
{
this.ID = inID;
this.Reference = (inReference == null) ? string.Empty : inReference;
}
public override string ToString()
{
return this.Reference;
}
}
我尝试使用下一个类将ComboBox的项目集合包装在自己的类型中。添加项目必须是具体类型。
您可以在此处添加其他所需的方法/属性(删除)
public class ComboBoxList<TCustomType>
{
private System.Windows.Forms.ComboBox.ObjectCollection _baseList;
public ComboBoxList(System.Windows.Forms.ComboBox.ObjectCollection baseItems)
{
_baseList = baseItems;
}
public TCustomType this[Int32 index]
{
get { return (TCustomType)_baseList[index]; }
set { _baseList[index] = value; }
}
public void Add(TCustomType item)
{
_baseList.Add(item);
}
public Int32 Count { get { return _baseList.Count; } }
}
这是一个派生自ComboBox的自定义组合框类
新增:泛型
public class ComboBoxCustomType<TCustomType> : System.Windows.Forms.ComboBox
{
public new ComboBoxList<TCustomType> Items;
public ComboBoxCustomType() : base()
{
this.Items = new ComboBoxList<TCustomType>(base.Items);
}
public new TCustomType SelectedItem
{
get { return (TCustomType)base.SelectedItem; }
}
}
下面的代码用于表单中。
private ComboBoxCustomType<Order> _cmbCustom;
private void ComboBoxCustomType_Initialize()
{
_cmbCustom = new ComboBoxCustomType<Order>();
_cmbCustom.Location = new Point(100, 20);
_cmbCustom.Visible = true;
_cmbCustom.DropDownStyle = ComboBoxStyle.DropDownList;
_cmbCustom.Items.Add(new Order(0, " - nothing - "));
_cmbCustom.Items.Add(new Order(1, "One"));
_cmbCustom.Items.Add(new Order(2, "Three"));
_cmbCustom.Items.Add(new Order(3, "Four"));
_cmbCustom.SelectedIndex = 0;
this.Controls.Add(_cmbCustom);
}
Items
以仅接受你的新类型,即使你从它继承; 但是你可以尝试将其包装在UserControl中并公开一个新的Items集合。虽然会有很多代码来模拟现有的属性和集合。当然,CBo已经接受了你特定的类型,只是不是仅仅那种类型。 - Ňɏssa Pøngjǣrdenlarpcombobox
事件中对项进行一些操作,则可以在您正在使用的每个事件处理程序中添加项类型检查...或为此控件命名为“ComboBoxOfMyType”,那么其他程序员将注意到这个combobox使用了某个类型。 - Fabio