简体   繁体   English

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

[英]List<string> Property for populating a ComboBox inside a UserControl - C#

I have a UserControl with a ComboBox inside. 我有一个带有ComboBox的UserControl。 I need to populate ComboBox items using a List property but I get the error below in designer: 我需要使用List属性填充ComboBox项,但在设计器中出现以下错误:

constructor on type 'system.string' not found

and Here is my code: 这是我的代码:

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

In general it's not a good idea to expose items of the ComboBox as a string[] or as a List<string> because users may set ComboItems[0] = "something" but it will not change the first element of the combo box items. 通常,将ComboBox项目公开为string[]List<string>并不是一个好主意,因为用户可以设置ComboItems[0] = "something"但不会更改组合框项目的第一个元素。

But if you are looking for a solution to get rid of the error message which you receive in designer, instead of a List<string> use a string[] and change your code to: 但是,如果您正在寻找一种解决方案来摆脱在设计器中收到的错误消息,请使用string[]而不是List<string>并将代码更改为:

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

Note 注意

This is the correct way of exposing Items property of a ComboBox in a UserControl : 这是在UserControl中公开ComboBox Items属性的正确方法:

[Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " +
    "System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
    typeof(UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ComboBox.ObjectCollection ComboItems {
    get { return comboBox1.Items; }
}

You can use ObjectCollection for your property and asign it directly to your combobox. 您可以将ObjectCollection用于属性,并将其直接分配到组合框。 This way you are allowed to use the design editor. 这样,您就可以使用设计编辑器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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