在Windows通用组合框窗体应用程序 [英] Generic ComboBox in Windows Forms Application

查看:148
本文介绍了在Windows通用组合框窗体应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从组合框派生的类,将只接受某些特定类型的对象。所以,我需要有一个通用的组合框。如果我宣布一个新的类是这样的:

I need to have a class derived from ComboBox that will only accept Objects of some specific type. So, I need to have a generic ComboBox. If I declare a new class like this:

public class GComboBox <Type> : ComboBox
{
 // Some code
}

然后 GComboBox 将不会出现Windows窗体在工具箱中。我如何让它出现在工具箱中,这样我可以把它放在那里,我就能够把任何其他来源的非通用组合框?

then GComboBox will not appear in the toolbox of Windows Form. How do I make it appear in the toolbox so that I can put it there as I would be able to put any other derived non-generic ComboBox?

推荐答案

一个通用的控制,你可以使用常规的子类,一个属性,而不是:

Instead of a generic Control you can use a regular subclass with a Property:

    public class GComboBox : ComboBox
    {
        public Type myType { get; set; }

        public GComboBox(Type type) { myType = type; }
        public GComboBox() { myType = typeof(int); }
        public override string ToString()
        {
            return "GComboBox<" +  myType.ToString() + ">";
        }
    }

这将在工具箱中显示为预期的。它默认为 System.Int32的,你应该把它放在如后适应在窗体构造函数中。

This will show up in the Toolbox as expected. It defaults to System.Int32 which you should adapt after placing it e.g. in the Form constructor..

    InitializeComponent();
    gComboBox1.myType =    typeof(Bitmap);

不知道你将如何$添加尽管p $ pvent错误的类型。有没有ItemAdded事件。 这个帖子 suggestes听着组合框的消息,但大部分帖子告诉你,你是无论如何增加项目的控制权。

Not sure how you would prevent wrong types being added though.. There is no ItemAdded event. This Post suggestes listening to the ComboBox messages but most posts tell you that you are in control of adding items anyway..

这篇关于在Windows通用组合框窗体应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆