UI语言如何改变?

时间:2012-05-19 15:45:57

标签: c# mvvm localization

在这里,我对UI语言有点困惑。如果语言改变了会发生什么?整个文件夹被更改或文化被加载?我无法得到实际发生的事情。

  Properties.Strings.MainWindow_Language_Selection_English_Label="English"
  Properties.Strings.MainWindow_Language_Selection_Gujarati_Label="ગુજરાતી"

请解释发生了什么。

  private void LanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem item = LanguageSelection.SelectedItem as ComboBoxItem;
        if (item.Content.ToString() == Properties.Strings.MainWindow_Language_Selection_English_Label)
        {
            CultureManager.UICulture = new System.Globalization.CultureInfo("en");
        }
        else if (item.Content.ToString() == Properties.Strings.MainWindow_Language_Selection_Gujarati_Label)
        {
            CultureManager.UICulture = new System.Globalization.CultureInfo("gu");
        }

        Settings.Default["UILanguage"] = CultureManager.UICulture.Name;
        Settings.Default.Save();
    }

1 个答案:

答案 0 :(得分:0)

通常,在应用程序线程上设置文化将在下一个显示的表单上生效,因此为了使这项工作,您可能需要一个登录/语言选择窗口,您可以在其中设置主线程的文化,然后显示应用程序的主窗口

有一些尝试可以使语言选择以immadiate方式生效(在WPF中更容易),但这就是开箱即用的方式。

但是,在WPF中,如果要直接将UI元素绑定到资源,则可以通过在资源属性上引发属性更改事件来进行UI更新。实现这一目标的最简单方法(除了为.resx文件创建新的代码生成器之外)就是将资源包装在这样的模型类中:

public class StringRes : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate {};

    public string Login
    {
        get { return Properties.Strings.Login; }
    }

    public string Password
    {
        get { return Properties.Strings.Password; }
    }

    public void NotifyLanguageChanged()
    {
        PropertyChanged(this, new PropertyChangedEventArgs("Login"));
        PropertyChanged(this, new PropertyChangedEventArgs("Password"));
    }
}

public class MainWindow
{
    private StringRes _resources;

    private void LanguageSelection_SelectionChanged()
    {
        System.Threading.Thread.CurrentThread.CurrentUICulture = GetCurrentCulture();
        _resources.NotifyLanguageChanged();
    }
}

如果已将UI元素绑定到StringRes类的实例,则在模型中引发通知更改事件时将更新它们。

相关问题