创建通用Windows窗体

时间:2017-10-16 20:24:04

标签: c# winforms

在我的工作中,我发现自己经常创造相同风格的窗体。我想移出重复的代码并创建一个模板来开始使用。

的新项目
 public partial class GenericForm<T> : Form
{

  private void InitializeComponent()
    {
     .
     .
     .
        this.pbProduction.Image = ((System.Drawing.Image)(resources.GetObject("pbProduction.Image")));

      }

尝试加载图片时出错

     {"Could not find any resources appropriate for the specified culture or the neutral culture. 
 Make sure \"SplitForm.GenericForm`1.resources\" was correctly embedded or linked into assembly \"SplitForm\" 
at compile time, or that all the satellite assemblies required are loadable and fully signed."}

我在哪里错了?

project Structure

2 个答案:

答案 0 :(得分:0)

从您的项目结构中,您尚未将图像添加为项目的资源。由于Properties文件夹未展开,我无法判断您的项目中是否有Ressources.resx文件。

你应该:

  • 右键单击您的项目和clic属性
  • 转到“资源”选项卡,创建一个资源文件(如果尚未完成)
  • 将您的图像添加为资源(将字符串中的资源类型更改为图像 并浏览到您的图片)
  • 现在您应该可以使用

    访问添加的资源

    this.pbProduction.Image = Properties.Resources.MyImageName

可在microsoft网站上找到更多信息 https://msdn.microsoft.com/en-us/library/3bka19x4(v=vs.100).aspx

答案 1 :(得分:0)

我知道什么是错的!在回答这个问题之前,我已经测试过通用类了!

第一步

你已经迈出了这一步。

使你的普通班通用。

public partial class GenericForm<T> : Form
{
    private void InitializeComponent()
    {
        this.pbProduction.Image = ((System.Drawing.Image)(resources.GetObject("pbProduction.Image")));
    }
}

第二步

使你的GenericForm.Designer.cs也是通用的,看来你的部分类是不一致的,两个类都应该是通用的

partial class GenericForm<T>
{
    //Don't touch the rest of the designer's code
}

第三步

重要提示:如果您的表单不是入口点,请跳过此步骤。

如果您的表单在应用程序启动时显示,则您需要修改Program.cs以添加通用类,例如,让我们使用string。< / p>

static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new GenericForm<string>());
    }
}

关于您的资源问题

这不是资源的运作方式!如果要使用资源中的图像,请使用以下代码:

Properties.Resources.<here's your resource's name>

您不需要直接使用.resx文件。只需在Project&gt;中添加图片即可。属性&gt;资源。
.resx文件是为视觉设计师设计的,而不是代码。