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

如何在WinUI 3中设置DatePicker为dd/MMM/yyyy日期格式?

解决WinUI 3 DatePicker显示格式改为dd/MMM/yyyy的问题

以下是几种可靠的解决方式,针对你设置文化未生效的情况:

方法一:直接指定DateTimeFormatter(最直接)

WinUI 3的DatePicker支持通过DateTimeFormatter自定义显示格式,无需依赖系统文化设置,步骤如下:

XAML中设置

<DatePicker CalendarIdentifier="GregorianCalendar">
    <DatePicker.DateFormatter>
        <!-- FormatString对应dd/MMM/yyyy格式:day=日,month.abbr=月份缩写,year=四位年 -->
        <DateTimeFormatter FormatString="day/month.abbr/year" />
    </DatePicker.DateFormatter>
</DatePicker>

代码后台设置

如果需要动态调整,可在代码中创建DateTimeFormatter并赋值:

using Windows.Globalization.DateTimeFormatting;

// 初始化DatePicker后设置
var dateFormatter = new DateTimeFormatter("day/month.abbr/year");
yourDatePicker.DateFormatter = dateFormatter;

方法二:修正文化设置的时机与范围

你之前设置CultureInfo的方式可能未覆盖WinUI 3的全局语言上下文,需补充设置ApplicationLanguages,并确保在App启动时执行:

using System.Globalization;
using Windows.Globalization;

protected override void OnLaunched(LaunchActivatedEventArgs args)
{
    // 设置.NET线程文化
    CultureInfo cultureInfo = new CultureInfo("sr-Latn-RS");
    CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
    CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

    // 设置WinUI全局语言覆盖,这一步是关键
    ApplicationLanguages.PrimaryLanguageOverride = "sr-Latn-RS";

    // 初始化窗口
    m_window = new MainWindow();
    m_window.Activate();
}

完成上述设置后,DatePicker会自动遵循sr-Latn-RS文化的日期格式(即dd/MMM/yyyy)。

为什么之前的设置无效?

WinUI 3的UI控件优先读取Windows.Globalization.ApplicationLanguages的设置,而非仅依赖.NET的CultureInfo。如果仅设置线程文化而未指定PrimaryLanguageOverride,控件可能不会应用预期的格式。

内容的提问来源于stack exchange,提问作者Mladen Gavrić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:45:03