如何改变文化



我正在尝试使用代码单击按钮来更改语言:

private void Spache_Click(object sender, RoutedEventArgs e)
{
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-FR");          
}

我的应用程序有一些资源文件:Resources.ar-TN.resxResources.fr-FR.resx等...我需要使用按钮切换语言。它在tha main中起作用,但是在按钮中它不起作用。

实际问题应该是:

更改UI文化后如何重新加载UI?

影响UI的属性是Thread.CurrentThread.CurrentUICulture不是 Thread.CurrentThread.CurrentCulture。第二种培养会影响琴弦解析或格式化的方式。CurrentUICulture是用于加载本地资源的文化。

更改CurrentUICulture不会重新加载这些资源。您必须明确强制重新加载或重新加载应用程序的主窗口。

检查WPF中的变化文化,由Pluralsight的作者撰写。该课程以WPF应用程序为例,因此请务必浏览它。您可以通过Microsoft(免费(Visual Studio Dev Essentials提供3个月的免费访问PluralSight课程。

文章显示的是,当文化变化时,如何明确处理主窗口并重新加载。

App.xaml经过修改,以防止主窗口自动打开。从App.xaml and the Onstartup`事件中删除了启动图书馆,以明确打开主窗口。这个:

<Application x:Class="WpfLocalized.App"
             ...
             StartupUri="MainWindow.xaml">
...
</Application>

更改为:

<Application x:Class="WpfLocalized.App"
             ...
             >
...
</Application>

,以下代码添加到App.xaml.cs

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Application.Current.MainWindow = new MainWindow();
        Application.Current.MainWindow.Show();
    }
    public static void ChangeCulture(CultureInfo newCulture)
    {
        Thread.CurrentThread.CurrentCulture = newCulture;
        Thread.CurrentThread.CurrentUICulture = newCulture;
        var oldWindow = Application.Current.MainWindow;            

        Application.Current.MainWindow = new MainWindow();
        Application.Current.MainWindow.Show();
        oldWindow.Close();
    }
}

OnStartup方法第一次加载主窗口。ChangeCulture改变了文化,关闭 当前窗口并再次加载它,从而重新加载了所有资源。

改变文化并重新加载所有要做的就是从按钮点击 App.ChangeCulture,例如:

    private void AUButton_Click(object sender, RoutedEventArgs e)
    {
        App.ChangeCulture(new CultureInfo("en-AU"));
    }

本文的示例具有一个单个文本框,其值是从资源和一些改变文化的按钮中加载的:

    <TextBlock
            Text="{x:Static resx:Resources.Greeting}"
            HorizontalAlignment="Center" Padding="10,5"
            Margin="5"/>

每次加载窗口时,资源将根据CurrentUculture

从正确的文件加载

另一个主题中有一个类似的问题,请检查一下,它可能是正确的

看看这是否有帮助

最新更新