【发布时间】:2013-10-28 17:03:53
【问题描述】:
我有一个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?我认为如果一次只使用 1 个PropertyGrid就可以实现您的目的,我们仍然需要更改Attribute的类型,但在选择对象之前,我们将相应地切换ReadOnly并且应该这样做把戏。
标签: c# .net winforms readonly propertygrid