我需要启用任意对象的编辑属性(对象的类型仅在运行时已知)。我创建了以下类:
public class Camera
{
[TypeConverter(typeof(ExpandableObjectConverter))]
public object Configuration
{
get
{
return configuration;
}
set
{
configuration = value;
}
}
public Class1 a;
[TypeConverter(typeof(ExpandableObjectConverter))]
public Class1 A
{
get
{
return a;
}
set
{
a = value;
}
}
}
选择对象“Camera”后,我可以在PropertyGrid上看到Class1的属性,但是我看不到对象“Configuration”的属性。我该如何解决这个问题?
答案 0 :(得分:1)
我的假设是您的表单在分配Configuration属性之前变得可见。您没有提供足够的代码来查看是否是这种情况。为了测试我的顾虑,我创建了两个配置对象:
public class Configuration1
{
public string Test { get; set; }
public byte Test1 { get; set; }
public int Test2 { get; set; }
}
和
public class Configuration2
{
public char Test3 { get; set; }
public List<string> Test4 { get; set; }
}
我修改了你的相机类看起来像这样:
public class Camera
{
public Camera()
{
Configuration1 = new Configuration1();
Configuration2 = new Configuration2();
}
private object configuration;
[TypeConverter(typeof(ExpandableObjectConverter))]
public object Configuration { get; set; }
[TypeConverter(typeof(ExpandableObjectConverter))]
public Configuration1 Configuration1 { get; set; }
[TypeConverter(typeof(ExpandableObjectConverter))]
public Configuration2 Configuration2 { get; set; }
}
然后我创建了一个带有PropertyGrid和两个Button实例的表单。我像这样配置了表单交互:
public partial class Form1 : Form
{
private readonly Camera camera = new Camera();
public Form1()
{
InitializeComponent();
propertyGrid1.SelectedObject = camera;
}
private void Button1Click(object sender, System.EventArgs e)
{
camera.Configuration = new Configuration2();
UpdatePropertyGrid();
}
private void Button2Click(object sender, System.EventArgs e)
{
camera.Configuration = new Configuration1();
UpdatePropertyGrid();
}
private void UpdatePropertyGrid()
{
propertyGrid1.Refresh();
propertyGrid1.ExpandAllGridItems();
}
}
启动视图如下所示:
点击第一个按钮后:
点击第二个按钮后:
如果删除刷新,则属性网格无法正常工作。另一种方法是在类和属性上提供带有INotifyPropertyChanged的接口。