我如何注入一个自定义UITypeEditor的一个闭源类型的所有属性?自定义、属性、类型、UITypeEditor

2023-09-02 01:50:38 作者:给你倾城的温柔

我想避免的,我已经写了一个自定义UITypeEditor的某种类型的每个实例放置EditorAttribute。

I want to avoid placing an EditorAttribute on every instance of a certain type that I've written a custom UITypeEditor for.

我不能放在类型的EditorAttribute因为我不能修改源。

I can't place an EditorAttribute on the type because I can't modify the source.

我有一个参考到将要使用的唯一的PropertyGrid实例

I have a reference to the only PropertyGrid instance that will be used.

我可以告诉PropertyGrid的实例(或所有实例),以使用自定义UITypeEditor的,每当遇到一个特定类型的?

Can I tell a PropertyGrid instance (or all instances) to use a custom UITypeEditor whenever it encounters a specific type?

这里是一个MSDN文章,它提供的关于如何做到这一点的起点。 NET 2.0或更高版本。

Here is an MSDN article that provides are starting point on how to do this in .NET 2.0 or greater.

推荐答案

您可以通过 TypeDescriptor.AddAttributes 通常副主编等在运行时。例如(在酒吧属性应该表现出一个...,显示编辑!):

You can usually associate editors etc at runtime via TypeDescriptor.AddAttributes. For example (the Bar property should show with a "..." that displays "Editing!"):

using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;

class Foo
{
    public Foo() { Bar = new Bar(); }
    public Bar Bar { get; set; }
}
class Bar
{
    public string Value { get; set; }
}

class BarEditor : UITypeEditor
{
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        MessageBox.Show("Editing!");
        return base.EditValue(context, provider, value);
    }
}
static class Program
{
    [STAThread]
    static void Main()
    {
        TypeDescriptor.AddAttributes(typeof(Bar),
            new EditorAttribute(typeof(BarEditor), typeof(UITypeEditor)));
        Application.EnableVisualStyles();
        Application.Run(new Form { Controls = { new PropertyGrid { SelectedObject = new Foo() } } });
    }
}