You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android端MAUI Blazor不遵循设备语言问题求助

Android端MAUI Razor Hybrid日期选择器语言不生效解决思路

1. 在Application级别提前初始化文化信息

MAUI Blazor的初始化流程可能早于MainActivity.OnCreate,仅在Activity中设置文化会导致Blazor上下文未捕获到该设置。创建自定义Application类,在其OnCreate方法中全局配置文化:

[Application]
public class CustomApplication : Application
{
    public CustomApplication(IntPtr handle, JniHandleOwnership ownership) : base(handle, ownership)
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();
        var targetCulture = new CultureInfo("it-IT");
        
        // 设置当前线程文化
        Thread.CurrentThread.CurrentCulture = targetCulture;
        Thread.CurrentThread.CurrentUICulture = targetCulture;
        
        // 设置默认线程文化,覆盖后续新建线程的默认值
        CultureInfo.DefaultThreadCurrentCulture = targetCulture;
        CultureInfo.DefaultThreadCurrentUICulture = targetCulture;
    }
}

修改AndroidManifest.xml的application节点,指定自定义Application:

<application android:name=".CustomApplication" ...>

2. 强制Blazor WebView应用目标文化

Blazor WebView的JS上下文可能独立于.NET文化设置,需通过JS互操作同步文化配置:

  1. 在wwwroot创建blazor-culture.js:
window.blazorCulture = {
    set: function (culture) {
        document.documentElement.lang = culture;
        localStorage.setItem('BlazorCulture', culture);
    }
};
  1. 在wwwroot/index.html中引用脚本:
<script src="blazor-culture.js"></script>
  1. 在Blazor页面(如Main.razor)中注入IJSRuntime并设置文化:
@inject IJSRuntime JSRuntime

@code {
    protected override async Task OnInitializedAsync()
    {
        await JSRuntime.InvokeVoidAsync("blazorCulture.set", "it-IT");
    }
}

3. 配置Android系统级语言支持

部分Android版本会限制应用的区域设置修改,需在Manifest中声明支持的语言并添加权限:

  1. 在AndroidManifest.xml中添加权限与配置:
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />

<application ...>
    <meta-data android:name="android.app.locale_config" android:resource="@xml/locales_config" />
</application>
  1. 在Resources/xml目录创建locales_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
    <locale>it-IT</locale>
</locale-config>

4. 确保控件绑定正确的文化

如果使用MAUI原生DatePicker/TimePicker,需明确绑定当前文化:

<DatePicker Culture="@CultureInfo.CurrentUICulture" />

若为自定义Blazor日期组件,需手动应用文化对应的格式:

var dateFormat = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;
// 将dateFormat应用到组件的显示格式中

内容的提问来源于stack exchange,提问作者Mr. Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 03:50:00