我有一个 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/