首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PropertyGrid问题

PropertyGrid问题
EN

Stack Overflow用户
提问于 2012-02-02 16:48:24
回答 2查看 1.6K关注 0票数 0

请考虑我的代码如下:

当我使用PropertyGrid控件向集合添加新字符串时,我得到了一个错误的Constructor on type 'System.String' not found.

代码语言:javascript
复制
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        propertyGrid1.SelectedObject = Class1.Instance.StringCollection;
    }
}

-----------------------------------------------------------------------------

public sealed class Class1
{
    private static Class1 _instance = new Class1();
    private List<string> _stringListCollection = new List<string>();

    public Class1()
    {
    }   

    public static Class1 Instance 
    {
        get { return _instance; }
    }

    public List<string> StringCollection
    {
        get { return _stringListCollection; }
        set { _stringListCollection  = value; }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-02 16:55:50

当您将列表分配给PropertyGrid时,它会尝试使用modify ...按钮显示单行,其中默认修改对话框要求Item类具有默认构造函数,这在string的情况下是不正确的

您可以创建具有默认构造函数和string属性的类,并分配该类的集合而不是string

或者,您可以使用EditorAttribute覆盖默认编辑器

希望这能有所帮助

票数 1
EN

Stack Overflow用户

发布于 2020-10-21 03:51:10

下面是一个小类,它实现了CollectionEditor并修复了字符串列表的问题:

代码语言:javascript
复制
public class CollectionEditorBase : CollectionEditor
{
    public CollectionEditorBase(Type type) : base(type) { }

    protected override object CreateInstance(Type itemType)
    {
        //Fixes the "Constructor on type 'System.String' not found." when it is an empty list of strings
        if (itemType == typeof(string)) return string.Empty;
        else return Activator.CreateInstance(itemType);
    }
}

现在只需更改要与字符串列表一起使用的编辑器:

代码语言:javascript
复制
public class MySettings
{
    [Editor(typeof(CollectionEditorBase), typeof(System.Drawing.Design.UITypeEditor))]
    public List<string> ListOfStrings { get; set; } = new List<string>();
}

然后在属性网格中使用MySettings的实例:

代码语言:javascript
复制
propertyGrid1.SelectedObject = new MySettings();

在类的顶部,您必须在代码中使用System.ComponentModel和System.ComponentModel.Design或完全限定这些名称。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9109370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档