List <string>用于在UserControl中填充ComboBox的属性 - C#

时间:2018-06-16 07:26:28

标签: c# .net winforms user-controls windows-forms-designer

我有一个带有ComboBox的UserControl。我需要使用List属性填充ComboBox项,但我在设计器中得到以下错误:

constructor on type 'system.string' not found

这是我的代码:

public List<string> comboItems
{
    get
    {
        List<string> n = new List<string>();
        foreach (var i in comboBox1.Items)
            n.Add(i.ToString());
        return n;
    }
    set
    {
        if (comboItems == null)
            comboItems = new List<string>();
        foreach (var i in value)
            comboBox1.Items.Add(i);
    }
}

2 个答案:

答案 0 :(得分:1)

一般情况下,将ComboBox的项目展示为string[]List<string>并不是一个好主意,因为用户可能会设置ComboItems[0] = "something",但它不会更改组合框项目的第一个元素。

但是,如果您正在寻找解决方案来摆脱设计师收到的错误消息,而不是List<string>使用string[]并将您的代码更改为:

public string[] ComboItems {
    get {
        return comboBox1.Items.Cast<object>()
                .Select(x => x.ToString()).ToArray();
    }
    set {
        comboBox1.Items.Clear();
        comboBox1.Items.AddRange(value);
    }
}

注意

这是在Items中公开ComboBox的{​​{1}}属性的正确方法:

UserControl

答案 1 :(得分:1)

您可以将ObjectCollection用于您的财产,并将其直接指向您的组合框。这样您就可以使用设计编辑器。

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ObjectCollection ComboItems
{
    get
    {
        return comboBox1.Items;
    }
    set
    {
        comboBox1.Items.Clear();
        foreach (var i in value)
            comboBox1.Items.Add(i);
    }
}