PropertyGrid对象级别的readonly属性

ref*_*ind 8 .net c# propertygrid propertydescriptor readonly-attribute

我想在我的中显示一个类的多个实例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; }
}
Run Code Online (Sandbox Code Playgroud)

我有很多类的实例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);
Run Code Online (Sandbox Code Playgroud)

这种方法运行得很好但不幸的是也只​​在类级别上.这意味着,如果我设定ValueisReadOnlyfalse,所有我的Parameter-objects拥有Value财产写入.但我只希望这个特定的对象(因此对象级).我真的不想为读/写和只读属性创建单独的类.

由于我的想法用完了,所以非常感谢你的帮助:)

提前致谢!

编辑:我需要将readonly属性显示为灰色,以便用户可以看到不允许或不可能编辑它们.

Adr*_*tti 5

编辑:链接的文章已被删除(我希望只是暂时的).您可以在如何在运行时向TypeDescriptor添加属性级属性的答案中找到可行的替代方案吗?.基本上你必须ReadOnlyAttribute通过TypeDescriptorfor属性添加(在运行时).


看看这个古老而美好的CodeProject上的文章,它包含了很多有用的工具PropertyGrid.

基本上,您提供了一个类或委托,用于获取属性的属性.因为它将被调用传递您想要获取属性的对象的实例,所以您将能够以ReadOnlyAttribute每个对象为基础返回(或不返回).简而言之:将a PropertyAttributesProviderAttribute应用于您的属性,编写您自己的提供程序并PropertyAttributes根据对象本身(而不是类)替换集合中的属性