如何在* .Designer.cs C#中替换标签文本的硬编码字符串?

时间:2013-11-19 06:32:09

标签: c# visual-studio hardcode

如何在Form1.Designers.cs中为标签正确替换硬编码字符串?

而不是:

        this.button1.Text = "TheButton";
        this.label1.Text = "TheLabel";

我想写:

        this.button1.Text = Resources.ButtonText;
        this.label1.Text = Resources.LabelText;

在可视化设计器中更改表单(添加任何组件并保存)后,VS代码生成器将标签文本转回硬编码字符串:

        this.button1.Text = Resources.ButtonText;
        this.label1.Text = "TheLabel";

有人知道如何解决这个问题吗?

3 个答案:

答案 0 :(得分:3)

Prevent Auto code change in Designer.cs for a specific line

using System;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
     {
       public Form1()
         {
           InitializeComponent();
           this.button1.Text = Resources.ButtonText;
         }
     }
}

答案 1 :(得分:2)

最简单的方法是制作自己的Button / Label,从Text获取Resources属性:

class MyButton: Button
{
    // put here attributes to stop its serialization into code and displaying in the designer
    public new string Text
    {
        get {return base.Text;}
        set {base.Text = value;}
    }

    public MyButton() : base()
    {
        base.Text = Resources.ButtonText;
    }
}

答案 2 :(得分:0)

刚刚找到了解决方案,以防止在designer.cs文件中恢复引用。

而不是

this.label1.Text = MyNamespace.Properties.Resources.gui_lable1_text;

制作

this.label1.Text = global::MyNamespace.Properties.Resources.gui_lable1_text;