问题
I have a class which is displayed in a property grid. One of the properties is a List<SomeType>
.
What's the easiest/correct way to set up the code so that I can add and remove items from this collection through the property grid, preferably using the standard CollectionEditor
.
One of the wrong ways is like this:
set not being called when editing a collection
User annakata suggest that I expose an IEnumerable
interface instead of a collection. Can someone please provide me with more details?
I have the extra complication that the collection returned by get
doesn't actually point to a member in my class, but is build on the fly from an other member, something like this:
public List<SomeType> Stuff
{
get
{
List<SomeType> stuff = new List<SomeType>();
//...populate stuff with data from an internal xml-tree
return stuff;
}
set
{
//...update some data in the internal xml-tree using value
}
}
回答1:
This is a slightly tricky one; the solution involves building with the full .NET Framework (since the client-only framework doesn't include System.Design
). You need to create your own subclass of CollectionEditor
and tell it what to do with the temporary collection after the UI is finished with it:
public class SomeTypeEditor : CollectionEditor {
public SomeTypeEditor(Type type) : base(type) { }
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) {
object result = base.EditValue(context, provider, value);
// assign the temporary collection from the UI to the property
((ClassContainingStuffProperty)context.Instance).Stuff = (List<SomeType>)result;
return result;
}
}
Then you have to decorate your property with the EditorAttribute
:
[Editor(typeof(SomeTypeEditor), typeof(UITypeEditor))]
public List<SomeType> Stuff {
// ...
}
Long and convoluted, yes, but it works. After you click "OK" on the collection editor popup, you can open it again and the values will remain.
Note: You need to import the namespaces System.ComponentModel
, System.ComponentModel.Design
and System.Drawing.Design
.
回答2:
As long as the type has a public parameterless constructor it should just work:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
class Foo {
private readonly List<Bar> bars = new List<Bar>();
public List<Bar> Bars { get { return bars; } }
public string Caption { get; set; }
}
class Bar {
public string Name { get;set; }
public int Id { get; set; }
}
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form {
Controls = { new PropertyGrid { Dock = DockStyle.Fill,
SelectedObject = new Foo()
}}});
}
}
来源:https://stackoverflow.com/questions/4145324/whats-the-correct-way-to-edit-a-collection-in-a-property-grid