Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

c# - What's the correct way to edit a collection in a property grid

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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...