2

我在 propertygrid 中定义项目。我的代码在这里:

[DisplayName("Title of book"), CategoryAttribute("Books")]
public string BookName{ get; set; }

使用此代码,我可以从 propertygrid 获取该项目的标签和价值(对于此示例:书名及其价值(例如)学习 C#):

private void button1_Click(object sender, EventArgs e)
{
    GridItem gi = propertyGrid1.SelectedGridItem;
    while (gi.Parent != null)
    {
        gi = gi.Parent;
    }
    foreach (GridItem item in gi.GridItems)
    {
        ParseGridItems(item); //recursive
    }
}

private void ParseGridItems(GridItem gi)
{
    if (gi.GridItemType == GridItemType.Category)
    {
        foreach (GridItem item in gi.GridItems)
        {
            ParseGridItems(item);
        }
    }
    textBox1.Text += "Lable : "+gi.Label + "\r\n";
    if(gi.Value != null)
        textBox1.Text += "Value : " + gi.Value.ToString() + "\r\n";
}

我怎样才能得到项目名称?对于这个例子:书名

4

2 回答 2

2

使用GridItem.PropertyDescriptor属性:

var propertyName = propertyGrid1.SelectedGridItem.PropertyDescriptor.Name;
于 2012-09-07T13:27:51.180 回答
0

如果继承 PropertyGrid 控件,则可以获取所有条目。在继承的类中,放置这个新属性:

public GridItem[] Items
    {
        get
        {
            try
            {
                System.Reflection.FieldInfo field_gridView = typeof(PropertyGrid).GetField("gridView", System.Reflection.BindingFlags.NonPublic
                    | System.Reflection.BindingFlags.Instance);

                object gridView = field_gridView.GetValue(this);

                System.Reflection.MethodInfo gridView_method_GetAllGridEntries = gridView.GetType().GetMethod("GetAllGridEntries", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[0], null);

                object gridEntries_collection = gridView_method_GetAllGridEntries.Invoke(gridView, new object[0]);

                System.Reflection.MethodInfo gridEntries_collection_count_method = gridEntries_collection.GetType().GetMethod("get_Count");

                int count_entries = (int) gridEntries_collection_count_method.Invoke(gridEntries_collection, new object[0]);

                System.Reflection.MethodInfo gridEntries_collection_getItem_method = gridEntries_collection.GetType().GetMethod("get_Item", new Type[] { typeof(int) });

                GridItem[] entries = new GridItem[count_entries];

                for (int i = 0; i < count_entries; i++)
                {
                    entries[i] = gridEntries_collection_getItem_method.Invoke(gridEntries_collection, new object[] { i }) as GridItem;
                }

                return entries;
            }
            catch
            {
                throw;
            }
        }
    }

希望对你有帮助,安本。

于 2014-02-19T15:34:01.687 回答