代码之家  ›  专栏  ›  技术社区  ›  Wim Coenen

修复通用UserControl的嵌入式资源

  •  26
  • Wim Coenen  · 技术社区  · 16 年前

    MyControl UserControl 所以我的课现在 MyControl<T> .

    MyControl`1.资源 找不到。快速浏览 .NET Reflector MyControl.resources ,没有 .

    MyControl<T>.InitializeComponent

     System.ComponentModel.ComponentResourceManager resources =
        new System.ComponentModel.ComponentResourceManager(
           typeof(MyControl<>));
    

    我如何强制 ComponentResourceManager MyControl.resources ?我们也欢迎其他解决这一问题的方法。

    4 回复  |  直到 14 年前
        1
  •  18
  •   Wim Coenen    16 年前

    事实证明,您可以通过继承来覆盖要加载的资源文件名 ComponentResourceManager 这样地:

       using System;
       using System.ComponentModel;
    
       internal class CustomComponentResourceManager : ComponentResourceManager
       {
          public CustomComponentResourceManager(Type type, string resourceName)
             : base(type)
          {
             this.BaseNameField = resourceName;
          }
       }
    

    现在,我可以确保资源管理器已加载 MyControl.resources 这样地:

     System.ComponentModel.ComponentResourceManager resources =
        new CustomComponentResourceManager(typeof(MyControl<>), "MyControl");
    

    这似乎奏效了。

    编辑 生成代码区域。我避免使用设计器,而是使用版本控制工具来还原任何不需要的更改,但解决方案并不理想。

        2
  •  17
  •   T. Fabre    13 年前

    除了Wim的技术,您还可以声明一个与泛型类同名的非泛型基控件,并使泛型控件/窗体从该非泛型基类派生。

    通过这种方式,您可以欺骗设计器和编译器使用泛型类中的资源文件,并且一旦设置了基类,您就可以获得永久的设计器支持,而无需在每次重建时修改.designer文件:

    // Empty stub class, must be in a different file (added as a new class, not UserControl 
    // or Form template)
    public class MyControl : UserControl
    {
    }
    
    // Generic class
    public class MyControl<T> : MyControl
    {
         // ...
    }
    

    唯一的要求是 确切地 泛型类及其基类的名称相同,并且基类必须在另一个类文件中,否则设计器会抱怨找不到这两个类中的一个。

    PS.我用表单测试了这个,但它应该和控件一样。

        3
  •  4
  •   Community Mohan Dere    5 年前

    在我的 Visual Studio 2008

    系统。组件模型。ComponentResourceManager资源=新系统。组件模型。组件资源管理器(类型(MyControl));

    使用泛型类型“WindowsFormsApplication1.UserControl1”需要“1”类型参数。

    请注意,在我的例子中,代码是在没有括号的情况下生成的, <> ,在类名之后。

    它变得有趣了,看 ImageList autogenerates non-compiling code in a Generic User Control .

    由微软于2005年7月6日下午2:49发布

        4
  •  4
  •   jnm2    12 年前

    最简单和最简单的解决方法是为自动生成的对象创建一个虚拟类 typeof() 。您不需要继承它,甚至不需要将其暴露在外部:

    // Non-generic name so that autogenerated resource loading code is happy
    internal sealed class GridEditorForm
    {
    }