winforms - 在运行时(动态)将 Editor/EditorAttribute 添加到对象的属性

标签 winforms attributes propertygrid my.settings

如何在运行时将 EditorAttribute (Editor) 添加到对象的属性?
我有 My.Settings.ExcludeFiles ,由设置设计器创建为 Public Property ExcludedFiles() As Global.System.Collections.Specialized.StringCollection .编辑时ExcludedFiles通过属性网格,“字符串集合编辑器”生成“未找到“System.String”类型的构造函数”运行时异常。
我无法更改 ExcludeFiles 的属性属性,因为它们将在下次进行任何设置更改时被覆盖。因此,我必须在运行时附加/添加 Editor/EditorAttribute。
我想要做的是添加 StringCollectionEditor在运行时,下面显示为设计时属性。

    <Editor(GetType(StringCollectionEditor), GetType(UITypeEditor))> _

解决方案
方法#1
TypeDescriptor.AddAttributes( _
    GetType(Specialized.StringCollection), _
    New EditorAttribute( _
        "System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", _
         GetType(System.Drawing.Design.UITypeEditor)))
您只需添加一次此属性,例如应用程序初始化。
方法#2
更灵活。见尼古拉斯·卡迪拉克
在下面回答 Adding Editor / EditorAttribute at Run-time (Dynamically) to an Object's Property .它使用派生的 CustomTypeDescriptor 和 TypeDescriptionProvider 类。您只需添加一次提供程序,例如应用程序初始化。

最佳答案

在给你我的第一个答案后,我想起了 Marc Gravell 给出的另一个我什至评论的解决方案。信不信由你,你只需要调用 TypeDescriptor.AddAttributes()。

这是在这里:How do I inject a custom UITypeEditor for all properties of a closed-source type? .

对于您的情况,它提供:

TypeDescriptor.AddAttributes(
    typeof(StringCollection),
    new EditorAttribute("System.Windows.Forms.Design.StringCollectionEditor,
        System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
        typeof(UITypeEditor)))

因此,也许您应该取消选中我之前的答案并确认此为解决方案(尽管所有功劳都归功于 Marc)。但是当您需要使用 TypeDescriptor 做更复杂的事情时,我之前的文章仍然为您提供了一个很好的技巧。

关于winforms - 在运行时(动态)将 Editor/EditorAttribute 添加到对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2043579/

相关文章:

c# - 当 Windows Shell 替换为 Windows Forms 应用程序时,第一次按键丢失

c# - 属性的目标可以从属性的实例派生吗?

asp.net-mvc-4 - 本地化比较属性

c# - Visual Studio 2015 中的隐藏/折叠属性

.net - 如何在属性网格中将 bool 属性显示为"is" |“否”?

c# - 从其 Processhandle 获取表单

c# - 如何将字符串发送到另一个窗口?

c# - 在 WinForms 上使用 TPL 进行并行编程

.net - 如何自动展开 PropertyGrid 中的 ExpandableObjectConverter 对象?

java - 有人知道 SWT 中的 PropertyEditor 或 PropertyGrid 之类的东西吗?