我有一个PropertyGrid
,用于显示辅助类中的属性。我将辅助类分配给PropertyGrid
,如下所示:
myPropertyGrid.SelectedObject = mySettingsHelper;
在助手类中,我在设计时像这样分配
ReadOnlyAttribute
:[DisplayName("DisplayExA"),
Description("DescriptionExA"),
ReadOnlyAttribute(true)]
public string PropertyA { get; set; }
[DisplayName("DisplayExB"),
Description("DescriptionExB"),
ReadOnlyAttribute(false)]
public string PropertyB { get; set; }
[DisplayName("DisplayExC"),
Description("DescriptionExC"),
ReadOnlyAttribute(true)]
public string PropertyC { get; set; }
但现在我需要能够在运行时动态地更改各个属性的此属性。根据某些条件,其中一些属性可能需要是只读或非只读的。我应该如何在运行时动态地进行更改?
编辑:
我尝试了以下代码,但这会为对象的每个实例设置ReadOnly属性!我想要对每个对象执行此操作。有时,一个对象可能将PropertyA设置为只读,而另一个对象可能将PropertyA设置为非只读。
public static class PropertyReadOnlyHelper
{
public static void SetReadOnly(object container, string name, bool value)
{
try
{
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(container.GetType())[name];
ReadOnlyAttribute attribute = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo fieldToChange = attribute.GetType().GetField("isReadOnly",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
fieldToChange.SetValue(attribute, value);
}
catch { }
}
}
PropertyGrid
?我认为如果一次只使用一个PropertyGrid
,你的目的就可以达到。我们仍然需要更改类型的Attribute
,但在选择对象之前,我们将根据需要切换ReadOnly
,这应该就能解决问题了。 - King King