如果你有资源文件,例如:
- Resources.resx
- Resources.hu-hu.resx
...并想在运行时更改本地化,
...并且不想弄乱额外的资源字典和重新编码所有 UI 本地化,
它适用于
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
但是它不会改变已经显示的窗口的语言。
要实现这一点,需要更多编码 - 必须管理应用程序生命周期,而不是默认的。
首先,从 App.xaml 中删除 StartupUri:
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ADUI.App"
xmlns:System="clr-namespace:System;assembly=mscorlib" >
<!--StartupUri="wndMain.xaml">-->
<Application.Resources>
</Application.Resources>
其次,实现一个类,它现在负责应用程序的生命周期:
public class LocApp: Application
{
[STAThread]
public static void Main()
{
App app = new App();
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
wndMain wnd = new wndMain();
wnd.Closed += Wnd_Closed;
app.Run(wnd);
}
private static void Wnd_Closed(object sender, EventArgs e)
{
wndMain wnd = sender as wndMain;
if (!string.IsNullOrEmpty(wnd.LangSwitch))
{
string lang = wnd.LangSwitch;
wnd.Closed -= Wnd_Closed;
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
wnd = new wndMain();
wnd.Closed += Wnd_Closed;
wnd.Show();
}
else
{
App.Current.Shutdown();
}
}
}
不要忘记将项目属性/应用程序页面上的启动对象更改为 LocApp!
最后,在主窗口的代码中实现一些切换语言的代码:
public partial class wndMain : Window
{
public string LangSwitch { get; private set; } = null;
// ... blah, blah, blah
private void tbEn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
LangSwitch = "en";
Close();
}
private void tbHu_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
LangSwitch = "hu-hu";
Close();
}
// ... blah, blah, blah
}
确保提供的本地化代码与 resx 文件语言代码之一匹配(本例中为“hu-hu”)!
此解决方案将使用所选语言关闭并重新打开主窗口,如果主窗口以其他方式关闭,则会退出。