如何使用 blazor 绑定时间类型的输入

How to bind input of type time with blazor

你好,我有 2int 类型的变量,我想绑定到 input 类型的 minmaxtime.
我该怎么做?

我不知道在 bind 字段中放置什么,因为有 2 个不同的变量。 还有 minmax 属性。

<input type="time" min="@model.min" max="@model.max" bind=?/>

我应该在 bind 中输入什么?

更新 在更彻底的分析中,我决定我将需要 2 个 Timespan 类型的变量,并将它们绑定到 2 个 time.

类型的输入

您不能将 TimeSpan 直接绑定到 Blazor 中的输入,但您可以使用 属性 将其转换为 to/from 字符串。

<input type="time" min="@model.min" max="@model.max" bind="@TimeProxy" />

@functions
{
  string TimeProxy { get => model.Time.ToString(); set => TimeSpan.TryParse(value,out model.Time); }
}

以前的解决方案不适用于 .net Core 3.1,因此我将添加一个更新的解决方案:

使用 Blazor :

<EditForm Model=@model OnValidSubmit="Submit">
    <InputText type="time" @bind-Value="TimeProxy" />
</EditForm>

代码更改也是必要的。

@code {
    // This field is required as you can not use property in out statement
    private TimeSpan LocalTime = TimeSpan.FromHours(0);
    private string TimeProxy { 
        get => model.Time.ToString();
        set => TimeSpan.TryParse(value,out LocalTime);
    }
    private void Submit() {
        model.Time = LocalTime;
        // following submit logic...
    }
}

我为此编写了一个小组件,它利用数据绑定并使用适当的数据类型。

用法:

<LabeledTime @bind-Value="shutdownDelay"></LabeledTime>

组件:

<label class="form-label" for="@LabelId">
    @ChildContent
</label>
<input id="@LabelId" type="time" value="@ValueInternal.ToString("hh\:mm")" step="60" @onchange="InternalValueChanged"/>

@code {

    private long LabelId = DateTime.Now.Ticks;

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public TimeSpan Value { get; set; }

    [Parameter]
    public EventCallback<TimeSpan> ValueChanged { get; set; }

    private TimeSpan ValueInternal { get; set; }

    protected override void OnParametersSet()
    {
        ValueInternal = Value;
        base.OnParametersSet();
    }

    private void InternalValueChanged(ChangeEventArgs obj)
    {
        if (!TimeSpan.TryParseExact(obj.Value.ToString(), "hh\:mm\:ss", null, out var result))
            return;

        ValueInternal = result;
        Value = result;
        ValueChanged.InvokeAsync(result);
    }
}

您还可以执行以下操作:

<input type="time" @bind="SomeTime" @bind:format="HH:mm"/>

@code {
    public DateTime SomeTime = new DateTime();

    private TimeSpan _time = SomeTime.TimeOfDay;
}

请注意,这不会直接绑定到 TimeSpan!