【发布时间】:2011-12-16 10:16:01
【问题描述】:
目前我正在尝试通过 PropertyGrid 配置我的一些类。如果类将属性作为接口提供,现在我在显示值(网格内的右侧)方面存在一些问题。我想,由于网格使用反射,它会采用真实类型并使用它在网格中显示值的正常方式。对于演示,只需使用下面的类层次结构并使用 PropertyGrid 创建一个简单的表单,然后通过调用将对象放入其中
propertyGrid1.SelectedObject = new MyContainerClass();
以下是课程:
public class MyContainerClass
{
// Simple properties that should be shown in the PropertyGrid
public MyInterface MyInterface { get; set; }
public MyClass MyClass { get; set; }
public object AsObject { get; set; }
public MyContainerClass()
{
// Create one instance of MyClass
var myClass = new MyClass();
// Put the instance into both properties
// (cause MyClass implements MyInterface)
MyClass = myClass;
MyInterface = myClass;
// and show it if it is declared as "object"
AsObject = myClass;
}
}
// Some kind of interface i'd like to show in the PropertyGrid.
public interface MyInterface
{
string Name { get; set; }
}
// A class that also implements the interface
// and uses some kind of TypeConverter
[TypeConverter(typeof(ExpandableObjectConverter))]
public class MyClass : MyInterface
{
// Create an instance and put something meaningful into the property.
public MyClass()
{
Name = "MyName";
}
public string Name { get; set; }
// Override ToString() to get something shown
// as value in the PropertyGrid.
public override string ToString()
{
return "Overridden ToString(): " + Name;
}
}
如您所见,容器在所有三个属性中都使用了相同的对象,但在网格中,您会在类属性和对象属性上看到 ToString() 文本,但在接口属性上什么也没有。此外,TypeConverter 仅用于使用确切类型的属性。
PropertyGrid showing MyContainer http://image-upload.de/image/O2CC5e/9558e4e179.png
有没有办法让 PropertyGrid 显示接口属性后面的类的 ToString() 结果?
【问题讨论】:
标签: c# winforms .net-4.0 propertygrid