如何在PropertyGrid C#中自定义PropertyInfo []对象

时间:2012-12-26 12:16:00

标签: c# propertygrid icustomtypedescriptor

我有一个动态加载的类,我事先并不知道它包含多少(或哪种类型)属性。 我希望将其所有属性加载到PropertyGrid中,以便在显示常规类时显示它。

例如,如果这是我的班级:

class TestPropertyObject
{
    [Category("Names")]
    [Description("Enter your name")]
    public string Name { get; set; }

    [Category("Numbers")]
    [Description("Enter your number")]
    public int Number { get; set; }
}

我用反射来生成一个对象并获得它的属性:

PropertyInfo[] info = obj.GetType().GetProperties()  

如何在PropertyGrid中显示属性?
我已经准备好了很多次这篇文章 http://www.codeproject.com/Articles/4448/Customized-display-of-collection-data-in-a-Propert 但我似乎无法让它发挥作用。

非常感谢一些指导。

谢谢!

1 个答案:

答案 0 :(得分:1)

这是一个解决方案,你只需要该类的实例。

        var OptionsPropertyGrid = new PropertyGrid();
        OptionsPropertyGrid.Size = new Size(300, 250);

        this.Controls.Add(OptionsPropertyGrid);

        TestPropertyObject appset = new TestPropertyObject();
        OptionsPropertyGrid.SelectedObject = appset;

此示例假设您的类的属性使用Category / description进行修饰。 如果我误解了它,请告诉我。

或者使用动态对象

        var OptionsPropertyGrid = new PropertyGrid();
        OptionsPropertyGrid.Size = new Size(300, 250);

        this.Controls.Add(OptionsPropertyGrid);
        this.Text = "Options Dialog";
        string classname = "WindowsFormsApplication1.TestPropertyObject";
        var type1 = Type.GetType(classname);
        object obj = Activator.CreateInstance(type1);
        OptionsPropertyGrid.SelectedObject = obj;

确保您能够获得该类的命名空间。

相关问题