如何使用属性设置自定义UITypeEditor的属性

本文关键字:属性 UITypeEditor 自定义 设置 何使用 | 更新日期: 2023-09-27 18:27:44

出于好奇,假设您有这样一个UITypeEditor:

public class CustomEditor : System.Drawing.Design.UITypeEditor
{
    public bool DoSomething { get; set; }
    [...]
}

并且您希望使用它来编辑DoSomething设置为true:的属性之一

public MyClass
{
    [EditorAttribute(typeof(CustomEditor), typeof(System.Drawing.Design.UITypeEditor))]
    public string MyProperty { get; set; }
    [...]
}

在安装编辑器时,如何指定要设置的CustomEditorDoSomething属性的值?这可能吗?或者你必须创建尽可能多的继承CustomEditor的类,以满足可能的配置数量?

如何使用属性设置自定义UITypeEditor的属性

在UITypeEditor.EditValue的实现中,您可以查看context参数以获得对正在编辑的属性描述符的引用。然后,您可以查看另一个属性,在该属性中放置编辑器配置值。

public class CustomEditor : System.Drawing.Design.UITypeEditor
{
   public override object EditValue(
       ITypeDescriptorContext context,
       IServiceProvider provider,
       object value)
   {
       var property = context.PropertyDescriptor;
       var config = (MyConfigAttribute)
           property.Attributes[typeof(MyConfigAttribute)];
       // ...
   }
}