我在我的應用程序中使用PropertyGrid。我需要在運行時更改自定義數據條件下的某些屬性的可見性和只讀屬性。尋找一個事件,當一個屬性的get被調用時觸發
雖然我沒有找到的東西容易&已經準備好了,我發現了一個解決方法在運行時,如下改變ReadOnlyAttribute
和BrowsableAttribute
屬性:
protected void SetBrowsable(string propertyName, bool value)
{
PropertyDescriptor property = TypeDescriptor.GetProperties(GetType())[propertyName];
BrowsableAttribute att = (BrowsableAttribute)property.Attributes[typeof(BrowsableAttribute)];
FieldInfo cat = att.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
if (property.Attributes.Cast<Attribute>().Any(p => p.GetType() == typeof(BrowsableAttribute)))
cat.SetValue(att, value);
}
protected void SetReadOnly(string propertyName, bool value)
{
PropertyDescriptor property = TypeDescriptor.GetProperties(GetType())[propertyName];
ReadOnlyAttribute att = (ReadOnlyAttribute)property.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo cat = att.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
if (property.Attributes.Cast<Attribute>().Any(p => p.GetType() == typeof(ReadOnlyAttribute)))
cat.SetValue(att, value);
}
現在,我的問題是,我應該調用這些方法?是否有任何事件可以爲object
調用這些方法?也許通過實現一個接口。