gpt4 book ai didi

c# - 如何为闭源类型的所有属性注入(inject)自定义 UITypeEditor?

转载 作者:太空狗 更新时间:2023-10-29 17:33:48 25 4
gpt4 key购买 nike

我想避免在我为其编写自定义 UITypeEditor 的特定类型的每个实例上放置 EditorAttribute。

我无法在类型上放置 EditorAttribute,因为我无法修改源。

我有一个将要使用的唯一 PropertyGrid 实例的引用。

我能否告诉 PropertyGrid 实例(或所有实例)在遇到特定类型时使用自定义 UITypeEditor?

Here是一篇 MSDN 文章,提供了如何在 .NET 2.0 或更高版本中执行此操作的起点。

最佳答案

您通常可以在运行时通过 TypeDescriptor.AddAttributes 关联编辑器等。例如(Bar 属性应该显示一个显示“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() } } });
}
}

关于c# - 如何为闭源类型的所有属性注入(inject)自定义 UITypeEditor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/849202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com