考虑下面的这个对话框,我该如何:
Create
按钮设为默认(或提交)按钮?MudTextField
在按回车(回车)键时提交?添加
ButtonType="ButtonType.Submit"
似乎没有改变任何东西。
<MudDialog IsVisible="true" Class="pa-4" >
<DialogContent>
<MudTextField @bind-Value="NewName" Label="Name" Variant="Variant.Outlined" />
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Filled" OnClick="CloseCreateNewNameDialog">Cancel</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="CreateNewName">Create</MudButton>
</DialogActions>
</MudDialog>
谢谢!
要提交创建按钮,您必须使用 MudBlazor 中的 Form 标签: https://mudblazor.com/components/form#simple-form-validation
<MudButton Variant="Variant.Filled" ButtonType="ButtonType.Submit" Color="Color.Primary" OnClick="CreateNewName">Create</MudButton>
并启用 MudTextField 在按键返回时提交,请使用 EventCallBacks OnKeyPress
使用 MudBlazor 提供的 KeyInterceptorFactory 可以使用更通用的方法,允许“订阅”表单中发生的任何按键。在下面的示例中,“Enter”键连接到验证并提交表单的事件处理程序。确保取消订阅该事件并处理 KeyInterceptor 实例。
@implements IDisposable
@using MudBlazor.Services
@inject IKeyInterceptorFactory KeyInterceptorFactory
...
<MudForm Model="@entity" @ref="@form">...</MudForm>
...
@code {
private string _elementId = "dialogcontainer_" + Guid.NewGuid().ToString().Substring(0, 8);
private IKeyInterceptor? _keyInterceptor;
protected bool IsJSRuntimeAvailable { get; set; }
MudForm? form;
protected override void OnAfterRender(bool firstRender)
{
IsJSRuntimeAvailable = true;
base.OnAfterRender(firstRender);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_keyInterceptor = KeyInterceptorFactory.Create();
await _keyInterceptor.Connect(_elementId, new KeyInterceptorOptions()
{
TargetClass = "mud-form",
Keys = {
new KeyOptions { Key="Enter", SubscribeDown = true },
},
});
_keyInterceptor.KeyDown += HandleKeyDown;
}
await base.OnAfterRenderAsync(firstRender);
}
internal void HandleKeyDown(KeyboardEventArgs args)
{
switch (args.Key)
{
case "Enter":
_ = Submit();
break;
}
}
private async Task Submit()
{
if (form != null)
{
await form.Validate();
if (form.IsValid)
{
SaveEntity();
}
}
}
void IDisposable.Dispose()
{
if (_keyInterceptor is not null)
{
_keyInterceptor.KeyDown -= HandleKeyDown;
}
if (IsJSRuntimeAvailable)
{
_keyInterceptor?.Dispose();
}
}