获取PropertyGrid的内容?

时间:2009-07-23 02:37:02

标签: c# propertygrid

我是C#的新手,很长一段时间的C ++程序员,我只是想知道一次使用.selectedObjects启动一个propertygrid。有没有办法在propertygrid中获取当前值的内容。

2 个答案:

答案 0 :(得分:0)

PropertyGrid不会将其内部公开给消费者。

但是,.Net允许您执行“Refelction”来检查代码的结构(并执行部分代码),包括类属性。

Here是一篇涵盖反思基础知识的文章。实际上,您可以看到更多带有反射的内部结构,而不是属性网格显示的内部结构。

答案 1 :(得分:0)

您必须使用对象类型中的反射来迭代网格中对象的所有属性。

object o = PropertyGrid.SelectedObject;
Type t = o.GetType();  // We will work on type "t"
List<MemberInfo> members = new List<MemberInfo>();
members.AddRange(t.GetProperties(BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance);  // Get the public instance properties list
foreach (MemberInfo member in members)
{
    Type type = null;
    object value = null;
    PropertyInfo pi = (member as PropertyInfo);
    type = pi.PropertyType;
    if (type.IsSubclassOf(typeof(CollectionBase)))
        continue;  // Sorry
    if (pi.GetCustomAttributes(typeof(NotSerializedAttribute), true).GetLength(0) > 0)
        continue;
    if (!pi.CanRead || !pi.CanWrite)
        continue;
    value = pi.GetValue(o, null);
    // TODO Print out, or save the "value"
}
相关问题