Winforms ComboBox用户控件绑定

时间:2014-07-15 06:15:56

标签: c# winforms data-binding combobox user-controls

我有一个继承自Combobox控件的用户控件。我想在用户控件的构造函数中绑定数据。但是当我将它添加到表单并运行项目时,它会显示重复的项目。

当我向winform添加控件时,它在表单的Designer文件中添加项目,当我运行项目时,它再次添​​加到用户控件的构造函数中。

public partial class CheckSeriesBox : ComboBox
{
    private static List<string> CheckSeries;

    public CheckSeriesBox()
    {
        InitializeComponent();

        CheckSeries = new List<string>();
        SetCheckSeries();

        this.Items.AddRange(CheckSeries.ToArray());
        this.SelectedIndex = 0;
    }

    public static List<string> SetCheckSeries()
    {
        CheckSeries.Add("A");
        CheckSeries.Add("B");
    }
}

1 个答案:

答案 0 :(得分:0)

http://social.msdn.microsoft.com/forums/vstudio/en-US/3e35b534-7d3f-4832-8859-b5cb838bd62a/extended-combobox-adds-items-twice

public partial class CheckSeriesBox : ComboBox
{
    private static List<string> CheckSeries;

    public CheckSeriesBox()
    {
        InitializeComponent();

        CheckSeries = new List<string>();
        SetCheckSeries();

        if (DesignMode)
        {
             this.Items.AddRange(CheckSeries.ToArray());
        }
    }

    public static List<string> SetCheckSeries()
    {
        CheckSeries.Add("A");
        CheckSeries.Add("B");
    }

    protected new bool DesignMode
    {
        get
        {
            if (base.DesignMode)
            {
                return true;
            }
            else
            {
                Control parent = this.Parent;
                while ((parent != null))
                {
                    System.ComponentModel.ISite site = parent.Site;
                    if ((site != null) && site.DesignMode)
                    {
                        return true;
                    }
                    parent = parent.Parent;
                }
                return false;
            }
        }
    }

}