请考虑我的代码如下:
当我使用PropertyGrid控件向集合添加新字符串时,我得到了一个错误的Constructor on type 'System.String' not found.。
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; }
}
}发布于 2012-02-02 16:55:50
当您将列表分配给PropertyGrid时,它会尝试使用modify ...按钮显示单行,其中默认修改对话框要求Item类具有默认构造函数,这在string的情况下是不正确的
您可以创建具有默认构造函数和string属性的类,并分配该类的集合而不是string
或者,您可以使用EditorAttribute覆盖默认编辑器
希望这能有所帮助
发布于 2020-10-21 03:51:10
下面是一个小类,它实现了CollectionEditor并修复了字符串列表的问题:
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);
}
}现在只需更改要与字符串列表一起使用的编辑器:
public class MySettings
{
[Editor(typeof(CollectionEditorBase), typeof(System.Drawing.Design.UITypeEditor))]
public List<string> ListOfStrings { get; set; } = new List<string>();
}然后在属性网格中使用MySettings的实例:
propertyGrid1.SelectedObject = new MySettings();在类的顶部,您必须在代码中使用System.ComponentModel和System.ComponentModel.Design或完全限定这些名称。
https://stackoverflow.com/questions/9109370
复制相似问题