如果你有资源文件,例如:
- 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" >
<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;
private void tbEn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
LangSwitch = "en";
Close();
}
private void tbHu_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
LangSwitch = "hu-hu";
Close();
}
}
确保提供的本地化代码与resx文件语言代码之一匹配(例如,在此示例中为“hu-hu”)!
此解决方案将使用选择的语言关闭并重新打开主窗口,并在主窗口由其他方式关闭时退出。