[英]How to create custom properties keypress event in propertygrid using vb.net or c#
[英]C# .Net 4.5 PropertyGrid: how to hide Properties
問題很簡單(我希望這有一個簡單的解決方案!):當它為零時,我想隱藏( Browsable(false) )屬性“Element”(在我的 PropertyGrid 對象中)。
public class Question
{
...
public int Element
{
get; set;
}
}
對我來說,在 PropertGrid 和自定義控件中隱藏屬性的最簡單方法是:
public class Question
{
...
[Browsable(false)]
public int Element
{
get; set;
}
}
要動態執行此操作,您可以使用此代碼,其中 Question 是您的類,您的屬性是 Element,因此您可以在不從集合中刪除元素的情況下顯示或隱藏它:
PropertyDescriptorCollection propCollection = TypeDescriptor.GetProperties(Question.GetType());
PropertyDescriptor descriptor = propCollection["Element"];
BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isBrow = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
//Condition to Show or Hide set here:
isBrow.SetValue(attrib, true);
propertyGrid1.Refresh(); //Remember to refresh PropertyGrid to reflect your changes
所以要完善答案:
public class Question
{
...
private int element;
[Browsable(false)]
public int Element
{
get { return element; }
set {
element = value;
PropertyDescriptorCollection propCollection = TypeDescriptor.GetProperties(Question.GetType());
PropertyDescriptor descriptor = propCollection["Element"];
BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isBrow = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
if(element==0)
{
isBrow.SetValue(attrib, false);
}
else
{
isBrow.SetValue(attrib, true);
}
}
}
}
您可以做的是重用我在此處對這個問題的回答中描述的DynamicTypeDescriptor
類: 找不到實體框架創建的屬性的 PropertyGrid Browsable,如何找到它?
像這樣的例子:
public Form1()
{
InitializeComponent();
DynamicTypeDescriptor dt = new DynamicTypeDescriptor(typeof(Question));
Question q = new Question(); // initialize question the way you want
if (q.Element == 0)
{
dt.RemoveProperty("Element");
}
propertyGrid1.SelectedObject = dt.FromComponent(q);
}
試試 BrowsableAttributes/BrowsableProperties 和 HiddenAttributes/HiddenProperties:
當我多年前想解決這個問題時,我記得,屬性 [Browsable] 不起作用。 我看到它現在工作得很好,但我也通過創建代理對象來解決問題。
有代碼: https ://github.com/NightmareZ/PropertyProxy
您可以使用屬性突出顯示所需的屬性,然后創建代理對象,該對象僅將突出顯示的屬性轉發到 PropertyGrid 控件。
public class Question
{
...
[PropertyProxy]
public int Element
{
get; set;
}
}
...
var factory = new PropertyProxyFactory();
var question = new Question();
var proxy = factory.CreateProxy(question);
propertyGrid.SelectedObject = proxy;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.