如何修改MAUI中DatePicker弹出框的白色背景色
MAUI DatePicker弹出框背景色修改方案
问题原因
你之前修改的是DatePicker控件本身的背景色,而点击弹出的选择框是平台原生弹窗,需要针对不同平台单独修改原生弹窗的样式。
解决方案
Android平台
Android中DatePicker点击后弹出的是DatePickerDialog,需要通过自定义Handler拦截弹窗创建并修改其背景:
public App() { InitializeComponent(); Microsoft.Maui.Handlers.DatePickerHandler.Mapper.AppendToMapping("CustomDatePickerDialog", (handler, view) => { #if ANDROID handler.PlatformView.Click += (s, e) => { var dialog = new Android.App.DatePickerDialog( Android.App.Application.Context, (o, args) => { view.Date = new DateTime(args.Year, args.Month + 1, args.DayOfMonth); handler.PlatformView.ClearFocus(); }, view.Date.Year, view.Date.Month - 1, view.Date.Day); // 设置弹窗背景色 dialog.Window.SetBackgroundDrawable(new Android.Graphics.Drawables.ColorDrawable(Android.Graphics.Color.LightGray)); dialog.Show(); e.Handled = true; }; #endif }); MainPage = new AppShell(); }
Windows平台
Windows的DatePicker弹出的是CalendarView,需要通过Handler修改其Flyout内的控件样式:
public App() { InitializeComponent(); Microsoft.Maui.Handlers.DatePickerHandler.Mapper.AppendToMapping("CustomDatePickerFlyout", (handler, view) => { #if WINDOWS if (handler.NativeView is Microsoft.UI.Xaml.Controls.DatePicker nativePicker) { nativePicker.CalendarViewStyle = new Microsoft.UI.Xaml.Style(typeof(Microsoft.UI.Xaml.Controls.CalendarView)) { Setters = { new Microsoft.UI.Xaml.Setter(Microsoft.UI.Xaml.Controls.CalendarView.BackgroundProperty, Colors.LightGray.ToNative()) } }; } #endif }); MainPage = new AppShell(); }
补充说明
- 你之前在
Style.xaml中设置的BackgroundColor仅作用于DatePicker控件本身,和弹出框无关,因此不会改变弹窗样式。 - 若需适配深色模式,可根据当前主题动态切换颜色值,比如Android中可结合系统主题获取对应颜色资源。
内容的提问来源于stack exchange,提问作者Arvind Chourasiya
相关产品推荐
相关产品推荐

