简体   繁体   中英

Best Way to Override ComboBox.Items

I've created an owner-draw user control that inherits from ComboBox.

The control stores specialized items, but the Items collection still accepts and returns items of type Object. Any tips on the best way to override this collection to be type-safe?

About the only way I can think of is to create my own collection class. The class wouldn't be a true collection--it would take an ObjectCollection as an argument to the constructor and simply extend the methods of that to.

The user control would pass the original Items collection to the constructor of the new class. And then override the Items property to return an instance of the new class instead.

This seems somewhat convoluted. Is there a better way?

You could do it a couple of different ways. First off, I'm a little confused about you creating a "user control" that inherits from ComboBox. You can create a custom control that inherits from ComboBox, but you cannot inherit from both UserControl (which is the usual definition of a "user control") and ComboBox.

If you define a true UserControl derivative, this gets a little easier. A UserControl, like I said, can't be a ComboBox, but it can have a ComboBox. So, you can drop and Dock a ComboBox to your UserControl surface, and then re-implement any properties you need to be able to use, such as Items. This will allow you to re-create Items as a collection of your choice, probably a strongly-typed List. The only problem will be knowing exactly what you'll want to re-implement; there's a lot of useful properties of a ComboBox that you won't be able to access in the Designer or in code unless you implement a "pass-through" property that modified the contained ComboBox within your UserControl.

If you inherit directly from ComboBox, it gets a little tricker in some ways, easier in others. You can hide the base class implementation of Items by defining your own and using the new keyword. You can change the visibility, type and other modifiers when you do this. This will prevent code that deals with your control as a CustomComboBox (or whatever you name it) from using the object array on the base class; they have to use your strongly-typed Items array. Your new property can still access the old one (which it will need to in order to make it work). You also get all the other public properties of a ComboBox for free; you only have to reimplement what you want to change. However, referring to your custom ComboBox as any base class will cause the runtime to use the version of Items that is valid for that class; that is, the object array, not your strongly-typed one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM