4

如何正确替换 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";

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

4

3 回答 3

3

防止在 Designer.cs 中为特定行自动更改代码

using System;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
     {
       public Form1()
         {
           InitializeComponent();
           this.button1.Text = Resources.ButtonText;
         }
     }
}
于 2013-11-19T06:37:37.807 回答
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;
    }
}
于 2013-11-19T06:40:26.830 回答
0

刚刚在designer.cs文件中找到了防止引用反转的解决方案。

代替

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

做了

this.label1.Text = global::MyNamespace.Properties.Resources.gui_lable1_text;
于 2018-05-28T06:18:32.780 回答