What is the easiest way to edit and persist a collection like decimal[]
or List<string>
in the WinForms designer?
The first problem is that a parameterless constructor is needed. So I made a simple wrapper class:
(at some point this was like MyObject<T>
, but the WinForms designercode generator didn't know how to handle it)
[Serializable()]
public class MyObject
{
public MyObject() {}
public decimal Value {get; set;}
}
In the container class we define a property and add the CollectionEditor attribute to it:
public class MyContainer
{
private List<MyObject> _col = new List<MyObject>();
[Editor(typeof(CollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
public List<MyObject> Collection
{
get { return _col; }
set { _col = value; }
}
}
Now I tried all sorts of things based on answers here on stackoverflow and articless on codeproject.com:
I did get it to work so that
However, by saving, closing and re-opening the form the elements in the collection are never persisted.
Edit: Hans gave me some tips (his comments somehow went into the void). I followed his guidelines and updated the source above, which unfortunately still doesn't work...
I recommend that if possible you expose a colletion property that is the same type as one already used in the framework and so you can reuse the existing collection editor. For example, if you use a StringCollection class then you can do the following and reuse the WinForms existing editor...
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor("System.Windows.Forms.Design.StringCollectionEditor,
System.Design, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public StringCollection Items
{
get { return _myStringCollection; }
}
Alternatively if you can expose a string[] then do this...
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor("System.Windows.Forms.Design.StringArrayEditor,
System.Design, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string[] Lines
{
get { return _myStringArray; }
set { myStringArray = value; }
}