4

我开发了一个本地化的应用程序,具有多语言界面。为此,我使用了 winform 的 localazible 功能以及语言字符串资源。到目前为止一切顺利,效果很好。

问题来了,当我必须尝试在后台工作进程中获取本地化字符串时:它不能使用当前的 UI 文化,而是使用默认值。ResourceManager 的 GetString 方法返回默认语言字符串,而不是 CurrentUICulture 的字符串。请注意,它在主线程中完美运行,问题出在 backgroundworker 内部。

那么,如何从后台工作线程中的语言资源文件中获取基于当前 ui 文化的本地化字符串?

环境:.net4、c#、Visual Studio 2010。

提前致谢!

4

2 回答 2

4

您需要在后台线程上设置 Thread.CurrentCulture 和 Thread.CurrentUICulture 属性以匹配前台线程的属性。这应该在后台线程上运行的代码开始时完成。

于 2011-04-14T20:03:03.130 回答
2

尽管这个问题的公认答案是绝对正确的,但我想用我在必须本地化一个相当大的系统后学到的东西来补充它。

每次需要使用 a 时设置Thread.CurrentCultureand非常容易出错且难以维护,特别是在系统的多个不同部分执行此操作时。为避免这种情况,您可以创建一个简单的类,该类继承自并始终在运行代码之前设置文化:Thread.CurrentUICultureBackgroundWorkerBackgroundWorker

public class LocalizedBackgroundWorker : BackgroundWorker {
    private readonly CultureInfo currentCulture;

    public LocalizedBackgroundWorker() {
        currentCulture = /* Get your current culture somewhere */
    }

    protected override void OnDoWork(DoWorkEventArgs e) {
        Thread.CurrentThread.CurrentCulture = currentCulture;
        Thread.CurrentThread.CurrentUICulture = currentCulture;
        base.OnDoWork(e);
    }
}

现在只需使用LocalizedBackgroundWorker该类而不是BackgroundWorker您就可以开始了。

于 2015-04-23T20:00:28.220 回答