[英]How to enumerate PropertyGrid items?
我有一個PropertyGrid
,並為其分配了一些對象。
var prpGrid = new PropertyGrid();
prp.SelectedObject = myObject;
我想得到所有網格項,我可以得到selectedGridItem屬性:
var selectedProperty = prpGrid.SelectedGridItem;
我可以這樣做嗎?
這是一段代碼,它將檢索屬性網格的所有GridItem對象:
public static GridItemCollection GetAllGridEntries(PropertyGrid grid)
{
if (grid == null)
throw new ArgumentNullException("grid");
object view = grid.GetType().GetField("gridView", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(grid);
return (GridItemCollection)view.GetType().InvokeMember("GetAllGridEntries", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, view, null);
}
當然,由於這是使用Property Grid的未記錄的私有字段,因此不保證將來可以使用:-)
擁有所有GridItem后,可以使用GridItem.GridItemType屬性過濾它們。
如果您只需要對象的屬性,則可以通過Reflection獲取這些屬性:
PropertyDescriptorCollection myObjectProperties = TypeDescriptor.GetProperties(myObject);
如果您使用BrowsableAttribute(false)
隱藏了某些屬性,則可以使用GetProperties(Type, Attribute[])
來過濾掉這些GetProperties(Type, Attribute[])
。
我不知道返回GridItem集合的方法。
更新
當然,您還可以通過Reflection獲取PropertyGrid用於標簽的字符串。
如果您使用DisplayNameAttribute("ABC")
裝飾屬性,則應該能夠通過GetCustomAttributes(Type, Boolean)
訪問DisplayName。 否則只需使用PropertyDescriptor的名稱。
還可以使用Parent屬性檢查解決方案@ C#選擇CategorizedAlphabetical排序的ProperyGrid中的第一行
我知道這是一個老問題,但我剛剛遇到了同樣的問題並使用此代碼解決了它(假設PropertyGrid
變量稱為grid
):
public void IteratePropertyGrid()
{
GridItemCollection categories;
if (grid.SelectedGridItem.GridItemType == GridItemType.Category)
{
categories = grid.SelectedGridItem.Parent.GridItems;
}
else
{
categories = grid.SelectedGridItem.Parent.Parent.GridItems;
}
foreach (var category in categories)
{
if (((GridItem)category).GridItemType == GridItemType.Category)
{
foreach (GridItem gi in ((GridItem)category).GridItems)
{
// Do something with gi
}
}
}
}
當然,此示例可以與簡單屬性網格一起使用,該網格只有一個級別的類別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.