【问题标题】:A PropertyGrid IssuePropertyGrid 问题
【发布时间】:2012-02-02 08:48:23
【问题描述】:

请考虑以下我的代码:

当我使用 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; }
    }
}

【问题讨论】:

  • 您的代码不正确。您可能将Class1.Instance 分配给了属性网格。通过分配Class1.Instance,然后按下StringCollection前面的''',然后按下添加按钮,你会得到你提到的错误。
  • 提供的代码没有编译有两个原因: Instance 没有指定类型,因为没有声明名为 Instance 的类。我认为它应该被键入 Class1。其次,名为 Form1 的事件处理程序是非法的,因为方法不能与它的封闭类型同名。我将其更改为 Form1_Load 并根据事件处理程序中的代码将其分配给 Load 事件。
  • 抱歉给大家带来了困惑。这不是我的实际代码,它更可能只是一个伪代码.. :)

标签: c#


【解决方案1】:

当您将某些内容分配给 PropertyGrid 时,它会尝试使用修改 ... 按钮显示单行, 其中默认修改对话框要求Item类有默认构造函数,这在字符串的情况下是不对的

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

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

希望对你有帮助

【讨论】:

  • 嗯...我会尽力回复您。感谢您的想法。
  • 我刚刚意识到......我希望这个类是静态的......所以创建一个实例是不可能的吗?......所以也不会创建 counstructor......我应该如何完成是吗?
  • 您可以使用自定义@yonan2236 覆盖编辑器,请参阅编辑后的帖子
  • stackoverflow.com/questions/6307006/…,在这里我找到了这个问题的更完整答案
【解决方案2】:

这是一个实现 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 或在代码中完全限定这些名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多