.NET Maui 7中如何修改DisplayAlert弹窗按钮文字颜色?
修改.NET Maui 7中DisplayAlert的按钮文字颜色
针对你遇到的DisplayAlert按钮文字为白色的问题,提供两种可行的解决方案:
方案一:通过自定义Handler替换原生弹窗逻辑
这种方式无需额外依赖,直接针对Android和iOS平台修改原生Alert控件的按钮文字颜色:
Android平台实现
- 在
MauiProgram.cs中注册自定义PageHandler:
builder.ConfigureMauiHandlers(handlers => { #if ANDROID handlers.AddHandler<Microsoft.Maui.Controls.Page, CustomPageHandler>(); #endif });
- 创建
CustomPageHandler类,重写DisplayAlert逻辑:
#if ANDROID using Android.App; using Android.Content; using Microsoft.Maui.Handlers; public class CustomPageHandler : PageHandler { protected override void ConnectHandler(Microsoft.Maui.Controls.Page view) { base.ConnectHandler(view); // 替换默认的DisplayAlert实现 view.DisplayAlert = async (title, message, accept, cancel) => { var alertDialog = new AlertDialog.Builder(Context) .SetTitle(title) .SetMessage(message); alertDialog.SetPositiveButton(accept, (sender, args) => { }); if (!string.IsNullOrEmpty(cancel)) { alertDialog.SetNegativeButton(cancel, (sender, args) => { }); } var dialog = alertDialog.Create(); dialog.Show(); // 设置按钮文字颜色(这里用红色和蓝色示例,可替换为你需要的颜色值) dialog.GetButton((int)DialogButtonType.Positive).SetTextColor(Android.Graphics.Color.ParseColor("#FF0000")); if (!string.IsNullOrEmpty(cancel)) { dialog.GetButton((int)DialogButtonType.Negative).SetTextColor(Android.Graphics.Color.ParseColor("#0000FF")); } var tcs = new TaskCompletionSource<bool>(); dialog.DismissEvent += (s, e) => { tcs.SetResult(dialog.GetButton((int)DialogButtonType.Positive).IsPressed); }; return await tcs.Task; }; } } #endif
iOS平台实现
- 同样在
MauiProgram.cs中注册自定义PageHandler:
builder.ConfigureMauiHandlers(handlers => { #if IOS handlers.AddHandler<Microsoft.Maui.Controls.Page, CustomPageHandler>(); #endif });
- 创建iOS版本的
CustomPageHandler:
#if IOS using UIKit; using Microsoft.Maui.Handlers; public class CustomPageHandler : PageHandler { protected override void ConnectHandler(Microsoft.Maui.Controls.Page view) { base.ConnectHandler(view); view.DisplayAlert = async (title, message, accept, cancel) => { var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); alertController.AddAction(UIAlertAction.Create(accept, UIAlertActionStyle.Default, action => { })); if (!string.IsNullOrEmpty(cancel)) { alertController.AddAction(UIAlertAction.Create(cancel, UIAlertActionStyle.Cancel, action => { })); } // 设置按钮文字颜色(示例为红色和蓝色) alertController.Actions[0].SetValueForKey(UIKit.UIColor.Red, new Foundation.NSString("titleTextColor")); if (alertController.Actions.Count > 1) { alertController.Actions[1].SetValueForKey(UIKit.UIColor.Blue, new Foundation.NSString("titleTextColor")); } var window = UIApplication.SharedApplication.KeyWindow; var viewController = window.RootViewController; while (viewController.PresentedViewController != null) { viewController = viewController.PresentedViewController; } var tcs = new TaskCompletionSource<bool>(); alertController.Dismissed += (s, e) => { tcs.SetResult(alertController.Actions[0].Clicked); }; viewController.PresentViewController(alertController, true, null); return await tcs.Task; }; } } #endif
方案二:使用自定义弹窗替代DisplayAlert
如果你需要跨平台统一的样式,推荐使用CommunityToolkit.Maui的Popup控件,完全自定义弹窗样式:
- 安装NuGet包:
Install-Package CommunityToolkit.Maui
- 在
MauiProgram.cs中注册工具包:
builder.UseMauiApp<App>().UseMauiCommunityToolkit();
- 创建自定义弹窗页面
CustomAlertPopup.xaml:
<?xml version="1.0" encoding="utf-8" ?> <toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" x:Class="YourAppNamespace.CustomAlertPopup" Size="300,200"> <VerticalStackLayout Padding="20" Spacing="15" BackgroundColor="White"> <Label Text="{Binding Title}" FontSize="Headline" HorizontalOptions="Center" TextColor="Black"/> <Label Text="{Binding Message}" FontSize="Body" HorizontalOptions="Center" TextColor="Gray"/> <HorizontalStackLayout Spacing="10" HorizontalOptions="End"> <Button Text="{Binding CancelText}" TextColor="Blue" BackgroundColor="Transparent" Clicked="CancelButton_Clicked"/> <Button Text="{Binding AcceptText}" TextColor="Red" BackgroundColor="Transparent" Clicked="AcceptButton_Clicked"/> </HorizontalStackLayout> </VerticalStackLayout> </toolkit:Popup>
- 弹窗后台代码
CustomAlertPopup.xaml.cs:
using CommunityToolkit.Maui.Views; namespace YourAppNamespace; public partial class CustomAlertPopup : Popup { public bool Result { get; private set; } public CustomAlertPopup(string title, string message, string acceptText, string cancelText) { InitializeComponent(); BindingContext = new { Title = title, Message = message, AcceptText = acceptText, CancelText = cancelText }; } private void AcceptButton_Clicked(object sender, EventArgs e) { Result = true; Close(); } private void CancelButton_Clicked(object sender, EventArgs e) { Result = false; Close(); } }
- 调用自定义弹窗:
var popup = new CustomAlertPopup("Sure ?", "Are you sure ?", "Yes", "No"); await this.ShowPopupAsync(popup); bool answer = popup.Result;
内容的提问来源于stack exchange,提问作者Thomas Carlton
相关产品推荐
相关产品推荐

