在运行时更改语言的正确方法 [英] Proper way to change language at runtime
问题描述
在运行时更改表单语言的正确方法是什么?
What is the proper way to change Form language at runtime?
- 使用递归手动设置所有控件,例如 这个
- 将语言选择保存到文件 > 重新启动应用程序 > 加载语言
InitializeComponent();
之前的选择 - 使用 Form 构造函数替换 active 的实例(如果可能的话)
- 别的东西
关于此问题的书面线索太多了,但没有一个提供真正的答案来说明什么是正确的方法?
There is so much half written threads about this but none provides real answer on what is proper way to do this?
更新:
澄清我的问题:
UPDATE:
To clarify my question:
做这样的事情:
public Form1()
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("de");
this.InitializeComponent();
}
工作正常,我的所有控件和资源中的所有其他内容都得到正确翻译.并执行以下操作:
works fine and all my controls and everything else in resources get translated correctly. And doing something like:
private void button1_Click(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
}
什么都不做,Form 保持在我之前设置的语言 InitializeComponent();
does nothing, Form stays in language I set up before InitializeComponent();
推荐答案
我相信 Hans Passant 评论中显示的解决方案可能是唯一的(通用)解决方案.
I believe the solution shown in Hans Passant's comment might be the only (general) solution.
就个人而言,我将这个基类用于所有需要本地化的表单:
Personally, I use this base class for all forms that need to be localized:
public class LocalizedForm : Form
{
/// <summary>
/// Occurs when current UI culture is changed
/// </summary>
[Browsable(true)]
[Description("Occurs when current UI culture is changed")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
[Category("Property Changed")]
public event EventHandler CultureChanged;
protected CultureInfo culture;
protected ComponentResourceManager resManager;
/// <summary>
/// Current culture of this form
/// </summary>
[Browsable(false)]
[Description("Current culture of this form")]
[EditorBrowsable(EditorBrowsableState.Never)]
public CultureInfo Culture
{
get { return this.culture; }
set
{
if (this.culture != value)
{
this.ApplyResources(this, value);
this.culture = value;
this.OnCultureChanged();
}
}
}
public LocalizedForm()
{
this.resManager = new ComponentResourceManager(this.GetType());
this.culture = CultureInfo.CurrentUICulture;
}
private void ApplyResources(Control parent, CultureInfo culture)
{
this.resManager.ApplyResources(parent, parent.Name, culture);
foreach (Control ctl in parent.Controls)
{
this.ApplyResources(ctl, culture);
}
}
protected void OnCultureChanged()
{
var temp = this.CultureChanged;
if (temp != null)
temp(this, EventArgs.Empty);
}
}
然后,我没有直接更改 Thread.CurrentThread.CurrentUICulture,而是在静态管理器类中使用此属性来更改 UI 文化:
Then instead of directly changing Thread.CurrentThread.CurrentUICulture, I use this property in static manager class to change UI culture:
public static CultureInfo GlobalUICulture
{
get { return Thread.CurrentThread.CurrentUICulture; }
set
{
if (GlobalUICulture.Equals(value) == false)
{
foreach (var form in Application.OpenForms.OfType<LocalizedForm>())
{
form.Culture = value;
}
Thread.CurrentThread.CurrentUICulture = value;
}
}
}
这篇关于在运行时更改语言的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!