you/How 可以在运行时为 PropertyGrid(PCL)指定编辑器吗?

Can you/How to specify Editor at runtime for PropertyGrid (for PCL)?

我在其中写了一个带有自定义对象的 PCL,然后我创建了一个 GUI 来处理来自 PCL 的对象...我尝试使用 PropertyGrid 来编辑属性。 ..我已经读过为了让网格知道如何处理对象,我需要指定 EditorAttribute 以及提供 TypeConverter ......但我不认为我可以在PCL...

有没有办法在 GUI 级别处理这个问题,比如告诉 PropertyGrid 在运行时使用特定类型的 Editor/TypeConverter?我浏览了网格的可用列表 function/properties,但看起来不可能。

您可以创建包含与原始 class 相同属性的元数据 class,并使用某些属性修饰元数据 class 的属性。然后告诉类型描述符使用元数据 class 为您的原始 class:

提供类型描述
var provider = new AssociatedMetadataTypeTypeDescriptionProvider(
    typeof(MyClass),
    typeof(MyClassMetadata));
TypeDescriptor.AddProvider(provider, typeof(MyPortableClass));

PropertyGrid 控件使用您的 class 的类型描述符来显示您的 class 的属性、它们的显示名称、它们的描述、它们的编辑器等等。您可以用不同的方式分配类型描述符。

对于您的情况,最好的解决方案是在 运行 时为您的 class 注册一个新的 TypeDescriptorProvider。这样您就可以在 运行 时更改 class 在 PropertyGrid 中的外观。

使用 AssociatedMetadataTypeTypeDescriptionProvider you can create a type descriptor provider for your class that uses a metadata class to provide type description. Then you can register the provider using TypeDescriptor.AddProvider.

通过这种方式,您可以为您的 class 引入元数据 class,其中包含属性的特性。

分步示例

  1. 将便携式 class 库添加到解决方案并向其添加 class:

    public class MyClass
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    }
    
  2. 将可移植 class 库的引用添加到您的 Windows Forms 项目。只要确保目标框架一致即可。

  3. System.DesignSystem.ComponentModel.DataAnnotations 引用添加到您的 Windows Forms 项目。

  4. 在 Windows Forms Project 中,为您的便携式 class 添加元数据 class。 class 应包含与原始 class:

    完全相同的属性
    public class MyClassMetadata
    {
        [Category("My Properties")]
        [DisplayName("First Property")]
        [Description("This is the first Property.")]
        public string Property1 { get; set; }
    
        [Category("My Properties")]
        [DisplayName("Second Property")]
        [Description("This is the second Property.")]
        [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
        public string Property2 { get; set; }
    }
    

    您需要添加这些用法:

    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.Design;
    using System.Drawing.Design; 
    
  5. 在表单的 Load 事件中,以这种方式为您的类型注册元数据提供程序:

    var provider = new AssociatedMetadataTypeTypeDescriptionProvider(
        typeof(MyClass),    
        typeof(MyClassMetadata));
    TypeDescriptor.AddProvider(provider, typeof(MyClass));
    
  6. 在 属性 网格中显示便携式 class 的实例:

    var myObject = new MyClass();
    this.propertyGrid1.SelectedObject = myObject ;
    

这是 运行 应用程序后的结果: