MudBlazor:如何从MudDialog向调用者返回参数?
MudDialog 返回值实现方法
1. 对话框内部处理返回值
在自定义对话框组件中,先注入DialogInstance,然后在确认操作时调用Dialog.Close()传入要返回的值:
@inject DialogInstance Dialog @inherits MudDialogComponent <!-- 对话框内容示例:输入框 --> <MudTextField @bind-Value="_inputValue" Label="输入要返回的字符串" /> <MudButton OnClick="OnConfirm" Variant="Variant.Filled" Color="Color.Primary">确认</MudButton> <MudButton OnClick="Dialog.Cancel" Variant="Variant.Outlined">取消</MudButton> @code { private string _inputValue; // 接收输入参数的定义(如果需要) [Parameter] public string InputParam { get; set; } private void OnConfirm() { // 用DialogResult.Ok包装要返回的值,传入Close方法 Dialog.Close(DialogResult.Ok(_inputValue)); } }
2. 调用方获取返回值
在调用对话框的页面/组件中,通过IDialogService打开对话框,等待结果后提取返回数据:
@inject IDialogService DialogService <MudButton OnClick="OpenDialog" Variant="Variant.Filled">打开对话框</MudButton> @code { private async Task OpenDialog() { // 构造对话框参数(如果需要传递输入参数) var parameters = new DialogParameters(); parameters.Add(nameof(YourDialogComponent.InputParam), "传入的初始参数"); // 打开对话框 var dialog = DialogService.Show<YourDialogComponent>("对话框标题", parameters); var result = await dialog.Result; // 判断是否为确认操作,提取返回值 if (!result.Canceled) { string returnedString = (string)result.Data; // 此处可对返回的字符串做后续业务处理 } } }
补充说明
- 若点击取消按钮,直接调用
Dialog.Cancel(),此时result.Canceled为true,result.Data为null。 - 返回值支持任意类型,只需在
DialogResult.Ok()中传入对应类型,调用方做相应类型转换即可。
内容的提问来源于stack exchange,提问作者ZedZip
相关产品推荐
相关产品推荐

