【发布时间】:2012-05-15 22:51:42
【问题描述】:
我想在我的PropertyGrid 中显示一个类的多个实例。该类如下所示:
public class Parameter
{
[Description("the name")]
public string Name { get; set; }
[Description("the value"), ReadOnly(true)]
public string Value { get; set; }
[Description("the description")]
public string Description { get; set; }
}
我在TreeView 中有许多该类的实例。当我在TreeView 中选择其中一个时,属性会按预期显示在PropertyGrid 中。到目前为止一切顺利,但我想通过以下方式自定义此行为:
对于每个实例,我希望能够防止用户修改特定属性。通过在我的类中设置ReadOnly(true)(如您在上面的示例中所见),所有Value 属性都将在类级别上被禁用。
经过一些研究,我发现了以下解决方案,它让我有机会在运行时启用/禁用特定属性:
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(this)["Value"];
ReadOnlyAttribute attr =
(ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo isReadOnly = attr.GetType().GetField(
"isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
isReadOnly.SetValue(attr, false);
这种方法效果很好,但不幸的是也只在类级别上。这意味着如果我将Value 的isReadOnly 设置为false,我的Parameter 对象的所有 都具有Value 可写属性。但我只希望在那个特定的对象上使用它(因此 object-level)。我真的不想为读/写和只读属性创建单独的类。
由于我的想法不多了,非常感谢您的帮助:)
提前致谢!
编辑:我需要将只读属性设为灰色,以便用户可以看到不允许或无法编辑它们。
【问题讨论】:
标签: c# .net propertygrid propertydescriptor readonly-attribute