开发者

C# Property for a list of classes

开发者 https://www.devze.com 2022-12-18 23:29 出处:网络
I\'m trying to use the property grid in the designer for Visual Studio. I have a list of classes that I want the developer to be able to add to at design time so that the user can have access to extr

I'm trying to use the property grid in the designer for Visual Studio.

I have a list of classes that I want the developer to be able to add to at design time so that the user can have access to extra features.

Here is some example code of what I have in the code already. The problem is when the developer goes to the design mode he can only see that there are x number of values in the list, but is unable to see any of the details. When trying to add a new item to the list the user is presented with an error.

Constructor on type 'EditorTextBox+SyntaxRegex' not found.

Now the code:

priva开发者_运维技巧te List<SyntaxRegex> _syntaxRegexList = new List<SyntaxRegex>();
public class SyntaxRegex
{
   public string title;
   public string regex;
   public Color color;
}
Public List<SyntaxRegex> SyntaxRegexList
{
   get{_syntaxRegexList = value;}
   set{return _regexList;}
}


You need to add type converters / editors; a good start would be to add:

[TypeConverter(typeof(ExpandableObjectConverter))]

above each class definition. For example, the following works fine (note I changed to properties, removed the list setter, etc):

[TypeConverter(typeof(ExpandableObjectConverter))]
class Foo {
    private List<SyntaxRegex> _syntaxRegexList = new List<SyntaxRegex>();
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class SyntaxRegex
    {
       public override string ToString() {
           return string.IsNullOrEmpty(Title) ? "(no title)" : Title;
       }
       public string Title { get; set; }
       public string Regex { get; set; }
       public Color Color { get; set; }
    }
    [DisplayName("Patterns")]
    public List<SyntaxRegex> SyntaxRegexList
    {
        get { return _syntaxRegexList; }
    }
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form
        {
            Controls =
            {
                new PropertyGrid { 
                    Dock = DockStyle.Fill,
                    SelectedObject = new Foo()
                }
            }
        });
    }
}

The specific error message also makes me wonder if your actual type is public with a public parameterless constructor (the fact that it doesn't compile makes me suspect you haven't posted the actual code...)

0

精彩评论

暂无评论...
验证码 换一张
取 消