为 MAUI Blazor 设置语言

2022年9月15日 2041点热度 2人点赞 0条评论
内容纲要

MAUI Blazor 在 Windows 上使用的是 WebView2,MAUI Blazor 运行环境是跟程序没关系的,即使是系统设置了中文语言,程序集设置了中文,本地文化设置了中文,CultureInfo 设置了中文,统统都没有用。

你可以在程序启动后,按下 F12,然后执行 JavaScript 代码,检查浏览器的运行环境是何种语言:

navigator.language
'en-US'

file

或者使用 API:

// using Windows.Globalization
var langs = ApplicationLanguages.Languages.ToList<string>();

file

坑 ①

首先,设置 Windows.Globalization:

            ApplicationLanguages.PrimaryLanguageOverride = "zh-CN";

然后重新启动程序,发现:

file

但是浏览器语言环境依然没有变化:
file

原因是 Preferences 文件需要重新生成才能起效,后面会提到。

坑 ②

程序启动后,会在 {Windows程序数据目录}/{你的程序ID}/LocalState\EBWebView\Default 下面生成一些 WebView2 的文件,其中 Preferences 文件,里面配置了 WebView2 的参数。

找到自己的程序数据目录:

var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;

file

因此,可以通过手动的方式修改文件,让 WebView2 使用中文环境。

file

file


var langs = ApplicationLanguages.Languages.ToList<string>();
var cultureInfo = CultureInfo.InstalledUICulture;
var index = langs.FindIndex((lang) => cultureInfo.Equals(CultureInfo.CreateSpecificCulture(lang)));
if (index > 0)
{
    ApplicationLanguages.PrimaryLanguageOverride = cultureInfo.Name;
    // "...this is immediately reflected in the ApplicationLanguages.Languages property."
    langs = ApplicationLanguages.Languages.ToList<string>();
}
var selectedLangs = string.Join(",", langs);
// Should check if this is the same as before but...
var preferences = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\EBWebView\\Default\\Preferences";
if (File.Exists(preferences))
{
    var jsonString = File.ReadAllText(preferences);
    var jsonObject = JObject.Parse(jsonString);    // using Newtonsoft.JSON
    //var intl = jsonObject["intl"];
    jsonObject["intl"] = JObject.Parse($@"{{""selected_languages"": ""{selectedLangs}"",""accept_languages"": ""{selectedLangs}""}}");
    jsonString = JsonConvert.SerializeObject(jsonObject);
        File.WriteAllText(preferences, jsonString);
}

坑 ③

最后我发现, ① 的思路是对的,不起效的原因是 Preferences 文件需要删除等重新创建才行,只要在程序启动时(WebView 尚未启动),设置中文即可。
file

file

检查代码:

    public static class MauiProgram
    {
        private static void SetWebViewLanguage()
        {
            ApplicationLanguages.PrimaryLanguageOverride = "zh-CN";

            var basePath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
            var preferencesFile = Path.Combine(basePath, "EBWebView/Default/Preferences"); // Preferences
            if (!File.Exists(preferencesFile)) return;

            var jsonString = File.ReadAllText(preferencesFile);
            var jsonObject = JsonObject.Parse(jsonString).AsObject();
            var languages = jsonObject["intl"]["selected_languages"].Deserialize<string>() ?? "";
            // "zh-CN,en,en-GB,en-US"
            if (!languages.StartsWith("zh-CN"))
            {
                // File.Delete(preferencesFile);
                jsonObject.Remove("intl");
                jsonObject.Add("intl", JsonObject.Parse("{\"selected_languages\":\"zh-CN,en,en-GB,en-US\"}"));
                jsonString = JsonSerializer.Serialize(jsonObject);
                File.WriteAllText(preferencesFile, jsonString);
            }
        }

public static MauiApp CreateMauiApp() 中使用:
file

痴者工良

高级程序员劝退师

文章评论