2

I have an application in which I need to edit some data, and PropertyGrid structure is visually the best candidate for my needs. However, PropertyGrid takes the public properties of an object and displays them in the grid. (additional options with attributes). However, I don't have such an object, because the list of key-value pairs I need to edit is dynamic.

The ideal solution would be something like this:

public class GridParam
{
    // ... several constructors here, one for each type
    // ... or a single one but with generic class, does not matter

    public String Name { get; set; }
    public Object Value { get; set; }
    public Type ItemType { get; set; }
}

GridParam stringParam = new GridParam("Address", "2534 Barkeley Av.");
GridParam numberParam = new GridParam("Year", 2012);

NewKindOfPropertyGrid grid = new NewKindOfPropertyGrid();
grid.AddParam(stringParam);
grid.AddParam(numberParam);

The above code would generate a property grid that looks like this: enter image description here

Is something like this possible with PropertyGrid or any other existing control (which at least looks similar to PG)? The syntax does not have to be similar to what I've written, but it would need to be able to accept a collection of such properties that can be dynamic, without having to define a class...

Kornelije Petak
  • 9,412
  • 15
  • 68
  • 96
  • see http://stackoverflow.com/questions/313822/how-to-modify-propertygrid-at-runtime-add-remove-property-and-dynamic-types-enu – Lonli-Lokli Feb 15 '12 at 08:02

1 Answers1

2

You have two options here.

The first (and simpler, IMO) is to implement the ICustomTypeDescriptor interface on a class that takes an IEnumerable<T> of your GridParam instances.

The PropertyGrid class doesn't actually use reflection directly; instead, it uses a TypeDescriptor class to get metadata about an instance of an object, which by default uses reflection.

However, if you implement ICustomTypeDescriptor, then the PropertyGrid will get all the information it would get from a TypeDescriptor from your implementation. You just have to feed it what you want it to show.

So in this case, you'd have the GetProperties implementation return a PropertyDescriptorCollection populated with a PropertyDescriptor for each of your GridParam instances.

The other, much more difficult (possibly) option is to dynamically create the type, and have it bind to that (since PropertyGrid takes an object to bind to). Of course, you're really replicating on some level most of what an implementation of ICustomTypeDescriptor would do, so it's probably better to go with the former.

casperOne
  • 73,706
  • 19
  • 184
  • 253