我有一个 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 { }
}
}
最佳答案
我能够使用此 CodeProject 中的库完全满足我的需要(只读属性的对象级分配)文章。很棒的是,它使我能够继续使用 .NET PropertyGrid
并仅使用自定义属性来处理动态设置。
关于c# - 在 PropertyGrid 中动态设置属性的只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19640823/