我有一个PropertyGrid
,我用它在助手类中显示属性。我给你的助手类的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; }
但现在我需要能够改变这一属性在运行时动态地显示各个属性。根据某些标准,这些属性中的某些属性可能需要是只读的或不是只读的。我如何在运行时动态地进行更改?
编辑:
我试着下面的代码,但这个设置只读属性为对象的每个实例!我想按照每个对象来做。有时一个对象可能具有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',并且应该这样做招。 –