【问题标题】:Winforms ComboBox User Control BindingWinforms ComboBox 用户控件绑定
【发布时间】:2014-09-05 05:28:21
【问题描述】:

我有一个继承自 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");
    }
}

【问题讨论】:

  • 请多写一行 if(CheckSeries.Count > 0) { CheckSeries.RemoveAll(); } 在调用 SetCheckSeries 方法之前
  • 还有一件事,而不是创建静态变量。如果符合您的目的,请使用公共财产。因为由于静态变量,它可能会在某些地方发生变化
  • @AshokRathod 当我将控件添加到我的 winform 时,它在表单的 Designer 文件中添加项目,当我运行项目时,它再次添​​加到用户控件的构造函数中。
  • 表示您的问题解决了吗?那么请将其标记为已解决
  • @AshokRathod 不,它没有解决。我无法解决这个问题。

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


【解决方案1】:

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;
            }
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2020-06-17
    相关资源
    最近更新 更多