【问题标题】:How to replace hardcoded string for label text in *.Designer.cs C#?如何在 *.Designer.cs C# 中替换标签文本的硬编码字符串?
【发布时间】:2013-11-19 06:32:08
【问题描述】:

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

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

【问题讨论】:

  • 所以你写Resources.LabelText;,VS把它转回"TheLabel";。是这样吗?
  • 是的,在设计器中更改表单后发生。
  • 放到表单构造函数中。设计器重新生成代码并将清除您的更改。
  • 自动生成器不会消除按钮文本的替换。即 this.button1.Text = Resources.ButtonText 在设计器中更改表单后仍然存在。

标签: c# visual-studio hardcode


【解决方案1】:

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;
         }
     }
}

【讨论】:

  • 这对我来说不是一个好的解决方案。我想在设计器中看到标签的文本,也不想复制任何代码。对于按钮,替换硬编码字符串非常有效,但对于标签则不行。
  • 很遗憾,但我没有找到更好的解决方案。
【解决方案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;
    }
}

【讨论】:

    【解决方案3】:

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

    代替

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

    做起来

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多