【问题标题】:List<string> Property for populating a ComboBox inside a UserControl - C#List<string> 用于在 UserControl 中填充 ComboBox 的属性 - C#
【发布时间】:2018-06-16 07:26:28
【问题描述】:

我有一个 UserControl,里面有一个 ComboBox。我需要使用 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);
    }
}

【问题讨论】:

  • 它对我很有效
  • 哪一行导致错误?
  • 行中没有错误,但是当您尝试通过 Visual Studio 属性窗口设计器将项目添加到列表时,它会显示 constructor on type 'system.string' not found 错误

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


【解决方案1】:

一般来说,将ComboBox 的项目公开为string[]List&lt;string&gt; 并不是一个好主意,因为用户可以设置ComboItems[0] = "something",但它不会更改组合框项目的第一个元素。

但是,如果您正在寻找一种解决方案来消除您在设计器中收到的错误消息,而不是 List&lt;string&gt;,请使用 string[] 并将您的代码更改为:

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

注意

这是在UserControl 中公开ComboBoxItems 属性的正确方法:

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

【讨论】:

  • 效果很好,我接受 :) 但为什么不使用 List 呢?问题出在哪里?使用列表将在设计器中为用户提供更好的编辑列表窗口,他可以通过单击添加按钮逐个添加项目,但使用string[] 他必须在文本编辑器中通过在每一行中按回车来添加项目。
  • 这是字符串编辑器的工作方式。我不确定是否有内置的CollectionEditor 支持字符串作为元素。
  • 关于您在 cmets 中的问题,我发布了一个答案 here。我想,您会发现选项 2 很有用。
【解决方案2】:

您可以将ObjectCollection 用于您的属性并将其直接分配给您的组合框。这样您就可以使用设计编辑器了。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多