MudBlazor中MudTable无法打开MudDialog的问题求助
MudTable点击编辑按钮无法弹出MudDialog的问题
问题现象
在Blazor Server项目中使用MudTable展示数据,点击每行的编辑按钮时,调试确认OpenDialog方法已触发,但绑定的MudDialog始终无法显示。
环境信息
- .NET版本:.NET 9
- MudBlazor版本:8.0.11
- 项目类型:Blazor Server App
问题原因
仅修改_dialogOpen的布尔值不会自动触发Blazor组件重新渲染,导致MudDialog无法感知状态变化;同时当前代码未给_selectedCompany赋值,后续编辑功能也无法正常工作。
解决方案
- 在
OpenDialog方法中调用StateHasChanged()强制组件重新渲染,让MudDialog检测到_dialogOpen的状态更新。 - 在
OpenDialog中为_selectedCompany赋值,传递当前行的公司数据,确保编辑时能获取到目标数据。
修改后的完整代码
<MudTable T="Company" items="@_Companies" Dense=true Hover=true Bordered=true Striped=true> <HeaderContent> <MudTh>Name</MudTh> <MudTh>Enabled</MudTh> <MudTh></MudTh> </HeaderContent> <RowTemplate> <MudTd DataLabel="Name">@context.Name</MudTd> <MudTd DataLabel="Enabled"> @if (context.Enabled) { <MudIcon Icon="@Icons.Material.Filled.Check" Color="Color.Success" /> } else { <MudIcon Icon="@Icons.Material.Filled.Close" Color="Color.Error" /> } </MudTd> <MudTd DataLabel="Actions" Class="d-flex justify-end"> <MudIconButton Icon="@Icons.Material.Outlined.Edit" Color="Color.Primary" Size="Size.Small" OnClick="@(() => OpenDialog(context))" /> </MudTd> </RowTemplate> </MudTable> <MudDialog @bind-Open="_dialogOpen" MaxWidth="MaxWidth.Small" CloseButton="true"> <DialogContent> <MudText Typo="Typo.h6">Edit</MudText> <MudTextField @bind-Value="_selectedCompany.Name" Label="Company Name" Margin="Margin.Normal" /> <MudCheckBox @bind-Value="_selectedCompany.Enabled" Label="Enabled" Margin="Margin.Normal" /> </DialogContent> <DialogActions> <MudButton Color="Color.Primary" OnClick="Save">Save</MudButton> <MudButton OnClick="Cancel">Cancel</MudButton> </DialogActions> </MudDialog> @code { private IEnumerable<Company> _Companies = new List<Company>(); private bool _dialogOpen = false; private Company _selectedCompany = new(); protected override void OnInitialized() { _Companies = new List<Company> { new Company("Company1"), new Company("Company2"), new Company("Company3") }; } private void OpenDialog(Company company) { // 复制当前公司数据到选中对象,避免直接绑定原数据导致实时变更 _selectedCompany = new Company(company.Name, company.Enabled); _dialogOpen = true; // 强制组件重新渲染,让MudDialog感知状态变化 StateHasChanged(); } private void Save() { var original = _Companies.FirstOrDefault(c => c.Name == _selectedCompany.Name); if (original != null) { original.Name = _selectedCompany.Name; original.Enabled = _selectedCompany.Enabled; } _dialogOpen = false; } private void Cancel() { _dialogOpen = false; } public class Company { public string Name { get; set; } public bool Enabled { get; set; } public Company() {} public Company(string name) { Name = name; Enabled = true; } public Company(string name, bool enabled) { Name = name; Enabled = enabled; } } }
内容的提问来源于stack exchange,提问作者Ferran Muñoz
相关产品推荐
相关产品推荐

