输入日期是一个非常重要的基础组件,可能也需要限定日期范围。这里只对日期进行定义,即设定type="date",其他的不常用,就略去了。DateTime 是一个结构体,像int有为0的初始值一样,它有一个初始值{0001/1/1 0:00:00};所以麻烦就在这里,要么就设为DateTime?,可这与codefirst相冲突;要么设定初始值,未设定初始值,需要在OnValidSubmit中再去判断日期字段是否未输入,即还是等于它的初始值。
DateBox.razor
@inherits InputBase<DateTime><div class="d-flex"><label class="control-label w-auto mt-2"><b>@Lable</b></label><div style="width:@InputWidth"><input type="date" value="@CurrentValueAsString" @onchange="EventCallback.Factory.CreateBinder<string?>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" class="form-control" disabled="@Disabled" @ref="Element" @attributes="AdditionalAttributes" /></div>
</div>
DateBox.razor.cs
public partial class DateBox : InputBase<DateTime>
{[Parameter]public required string Lable { get; set; }[Parameter]public string InputWidth { get; set; } = "300";[Parameter]public bool Disabled { get; set; }[Parameter]public DateTime? MaxDate { get; set; }[Parameter]public DateTime? MinDate { get; set; }private const string DateFormat = "yyyy-MM-dd";protected override void OnParametersSet(){base.OnParametersSet();Lable += ":";InputWidth += "px;";Dictionary<string, object> keyValues = new();if (MaxDate.HasValue){keyValues.Add("max", MaxDate.Value.ToString("yyyy-MM-dd"));}if (MinDate.HasValue){keyValues.Add("min", MinDate.Value.ToString("yyyy-MM-dd"));}AdditionalAttributes = keyValues;}[DisallowNull] public ElementReference? Element { get; protected set; }/// <inheritdoc />protected override string FormatValueAsString(DateTime value)=> value switch{DateTime dateTimeValue => BindConverter.FormatValue(dateTimeValue, DateFormat, CultureInfo.InvariantCulture),//_ => string.Empty, // Handles null for Nullable<DateTime>, etc.};/// <inheritdoc />protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out DateTime result, [NotNullWhen(false)] out string? validationErrorMessage){if (BindConverter.TryConvertTo(value, CultureInfo.InvariantCulture, out result)){//Debug.Assert(result != null);validationErrorMessage = null;return true;}else{validationErrorMessage = "所填日期不正确!";return false;}}
}
使用:
<DateBox Lable="日期测试" InputWidth="200" @bind-Value="myClass.Date" MaxDate="@maxDate" MinDate="@minDate"></DateBox>@code{private DateTime maxDate = DateTime.Today;private DateTime minDate = new DateTime(2022, 1, 1);}