如何在.NET MAUI中自定义DisplayAlert使消息文本加粗?
实现自定义加粗文本弹窗的方案
原生的DisplayAlert不支持富文本格式,要实现加粗消息的弹窗,得自己写自定义弹窗页面来搞定,具体步骤如下:
1. 创建自定义弹窗页面
在项目里新建一个ContentPage(比如命名为BoldAlertPage.xaml),布局里包含标题、加粗消息文本和确认按钮:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourNamespace.BoldAlertPage" BackgroundColor="#80000000" Padding="20"> <VerticalStackLayout HorizontalOptions="Center" VerticalOptions="Center" BackgroundColor="White" CornerRadius="10" Padding="25"> <!-- 标题 --> <Label Text="{Binding Title}" FontSize="Large" FontAttributes="Bold" HorizontalOptions="Center"/> <!-- 加粗的消息文本 --> <Label Text="{Binding Message}" FontSize="Medium" FontAttributes="Bold" Margin="0,15,0,20" HorizontalOptions="Center"/> <!-- 确认按钮 --> <Button Text="OK" Command="{Binding CloseCommand}" WidthRequest="100"/> </VerticalStackLayout> </ContentPage>
2. 编写弹窗页面的ViewModel
新建对应的ViewModel(BoldAlertPageViewModel.cs),处理标题、消息和关闭逻辑:
using System.Windows.Input; using Microsoft.Maui.Controls; namespace YourNamespace; public class BoldAlertPageViewModel { public string Title { get; set; } public string Message { get; set; } public ICommand CloseCommand { get; } public BoldAlertPageViewModel(string title, string message, Action closeAction) { Title = title; Message = message; CloseCommand = new Command(() => closeAction?.Invoke()); } }
3. 完善弹窗页面的代码后置逻辑
在BoldAlertPage.xaml.cs里绑定ViewModel,并设置弹窗关闭的逻辑:
namespace YourNamespace; public partial class BoldAlertPage : ContentPage { public BoldAlertPage(string title, string message) { InitializeComponent(); BindingContext = new BoldAlertPageViewModel(title, message, () => Navigation.PopModalAsync()); } }
4. 替换原有ViewModel中的ShowAlert方法
把原来调用原生DisplayAlert的方法,改成弹出自定义弹窗:
private async Task ShowAlert(string title, string message) { await Application.Current.MainPage.Navigation.PushModalAsync(new BoldAlertPage(title, message)); }
这样就能实现带加粗消息文本的弹窗,完全不需要依赖第三方包。如果要调整弹窗样式(比如背景色、按钮样式、文本对齐方式等),直接修改自定义弹窗的XAML即可。
内容的提问来源于stack exchange,提问作者JuliusB
相关产品推荐
相关产品推荐

