我有一个应用程序,我需要编辑一些数据,而PropertyGrid结构在视觉上是我需要的最佳候选者。但是,PropertyGrid获取对象的公共属性并将其显示在网格中。 (带属性的附加选项)。但是,我没有这样的对象,因为我需要编辑的键值对列表是动态的。
理想的解决方案是这样的:
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);
上面的代码会生成一个如下所示的属性网格:
使用PropertyGrid或任何其他现有控件(至少看起来与PG相似)是否可以这样? 语法不必与我编写的类似,但它需要能够接受可以是动态的这类属性的集合,而不必定义类...
答案 0 :(得分:2)
这里有两个选择。
第一个(也就是更简单的IMO)是在ICustomTypeDescriptor
interface个GridParam
个实例的类上实现IEnumerable<T>
。
PropertyGrid
class实际上并不直接使用反射 ;相反,它使用TypeDescriptor
class来获取有关对象实例的元数据,默认情况下使用反射。
但是,如果您实施ICustomTypeDescriptor
,那么PropertyGrid
将从您的实施中获得从TypeDescriptor
获得的所有信息。你只需要提供你想要它显示的东西。
因此,在这种情况下,GetProperties
实施的每个GridParam
实例都会PropertyDescriptorCollection
填充PropertyDescriptor
。
另一个更困难的(可能)选项是动态创建类型,并将其绑定到该类型(因为PropertyGrid
需要object
绑定到)。当然,你真的在某种程度上复制了ICustomTypeDescriptor
的一个实现,所以最好与前者一起使用。