I have PropertyGridone that I used to display properties in a helper class. I assign a helper class PropertyGridas follows:
myPropertyGrid.SelectedObject = mySettingsHelper;
In the helper class, I assign ReadOnlyAttributeduring development as follows:
[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; }
But now I need to be able to change this attribute on individual properties dynamically at runtime. Based on certain criteria, some of these properties may be required to be read-only or not only read-only. How to make a dynamic change at runtime?
EDIT:
, 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 { }
}
}