简体   繁体   English

C# - 从另一个 Class 更改 Label 已打开表单中的文本

[英]C# - Change Label Text in opened Form from another Class

I am coding a Program in C# using WinForms which has language Support, means a user can for example change the Program Language from English to German.我正在使用具有语言支持的 WinForms 在 C# 中编写程序,这意味着用户可以例如将程序语言从英语更改为德语。

Now I have Form1 with Label1 and a Class1 .现在我有Form1Label1Class1

Class1 has a public void method named Translate() and it should translate the text of the Label1 . Class1有一个名为Translate()的公共 void 方法,它应该翻译Label1的文本。 It does that by executing Translate() at the Form1 Load Event but which doesn't work for me.它通过在Form1加载事件中执行Translate()来做到这一点,但这对我不起作用。

I tried it with the following code in Form1 :我在Form1中使用以下代码进行了尝试:

 private void Form1_Load(object sender, EventArgs e)
    {
        new Class1(Translate());
    }

Code in Class1 : Class1中的代码:

 public void Translate()
    {
        if (Language.Equals(1))
        {
            new Form1().Label1.Text = "English Translated Text";
        }
        else if(Language.Equals(2))
        {
            new Form1().Label1.Text = "German Translated Text";
        }
    }

It probably doesn't work since It changes the Text Label at a new Form instead of changing it on the already opened form but I don't know how to make it work using the code that I already have.它可能不起作用,因为它将文本 Label 更改为新表单,而不是在已打开的表单上更改它,但我不知道如何使用我已有的代码使其工作。

As suggested, pass the Form via this :按照建议,通过this方式传递表单:

private void Form1_Load(object sender, EventArgs e)
{
    Class1 c1 = new Class1();
    c1.Translate(this));
}

In Translate() :Translate()中:

public void Translate(Form1 f1)
{
    if (Language.Equals(1))
    {
        f1.Label1.Text = "English Translated Text";
    }
    else if(Language.Equals(2))
    {
        f1.Label1.Text = "German Translated Text";
    }
}

*This assumes, however, that Label1 is publicly accessible on Form1. *但是,这假设Label1可在 Form1 上公开访问。 Controls are not publicly accessible by default.默认情况下,控件不可公开访问。 To fix this, change the Modifiers property of Label to public.要解决此问题, LabelModifiers属性更改为 public。

But the real solution lies in implementing Localization .但真正的解决方案在于实施Localization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM