这是一个带标签和验证信息的输入框,用起来很方便。为避免命名冲突,这里将InputText改名为TextBox,其实内部类型就是string。
TextBox.razor
@inherits InputBase<string?>
<div class="d-flex">
<label class="control-label w-auto mt-2"><b>@Lable</b></label>
<div style="width:@InputWidth">
<input type="text" @bind-value="CurrentValue" multiple="@AdditionalAttributes" class="form-control" disabled="@Disabled" @ref="Element"/>
<span class="w-100"><ValidationMessage For="ValueExpression" /></span>
</div>
</div>
TextBox.razor.cs
public partial class TextBox : InputBase<string?>
{
[Parameter]
public required string Lable { get; set; }
[Parameter]
public string InputWidth { get; set; } = "300";
[Parameter]
public bool Disabled { get; set; }
[DisallowNull] public ElementReference? Element { get; protected set; }
protected override void OnParametersSet()
{
base.OnParametersSet();
Lable += ":";
InputWidth += "px;";
}
protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out string? result, [NotNullWhen(false)] out string? validationErrorMessage)
{
result = value;
validationErrorMessage = null;
return true;
}
}
注意,组件的总长不能大于上一级容器长度,否则标签会分行或断行。
使用:
<TextBox Lable="单位名称" @bind-Value="model.CompanyName" InputWidth="500"/>
可能有人会说用反射获取标签,我认为上面这个代码非常明显地显示了这是哪个属性输入框,用反射反而查找起来不容易。
效果:
另外,哪位高手说一下,InputText 源码中有个属性不懂,能否帮忙解释下:
[DisallowNull] public ElementReference? Element { get; protected set; }