我想在我的 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
-objects 具有可写的 Value
属性。但我只希望在那个特定对象上执行此操作(因此对象级别)。我真的不想为读/写和只读属性创建单独的类。
由于我没有想法,非常感谢您的帮助:)
提前致谢!
编辑:我需要将只读属性显示为灰色,以便用户可以看到不允许或不可能编辑它们。
最佳答案
编辑:链接的文章已被删除(我希望只是暂时的)。您可以在 How to add property-level Attribute to the TypeDescriptor at runtime? 的答案中找到一个可行的替代方案.基本上,您必须(在运行时)通过 TypeDescriptor
为该属性添加 ReadOnlyAttribute
。
看看这古老而美好的article on CodeProject ,它包含许多用于
PropertyGrid
的有用工具。
基本上,您提供一个类或一个委托(delegate),用于获取属性的特性。因为它将被调用并传递您想要获取属性的对象的实例,所以您将能够返回(或不返回)基于每个对象的 ReadOnlyAttribute
。很快:将 PropertyAttributesProviderAttribute
应用于您的属性,编写您自己的提供程序并根据对象本身(而不是类)替换 PropertyAttributes
集合中的属性
关于c# - 对象级的 PropertyGrid 只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10481940/