我试图将日期输入中选择的日期强制为用户实际选择的日期所在周的周日。因此,如果他们选择周三,它实际上会改为同一周的周日。
我已经做到了,但当我再次在同一周重新选择日期时,它就不起作用了。例如,当用户选择周三时,它成功地选择了周日。但当他们选择星期二时,它会将显示的值保持为星期二,而不是将其更改为星期天(这是我希望它做的(
下面是一些示例代码
<input type="date" value="@overrideStart.ToString("yyyy-MM-dd")" @onchange="@SelectStartOfWeek" />
@code {
private DateTime overrideStart = DateTime.Today;
protected override async Task OnInitializedAsync()
{
overrideStart = GetStartOfWeek(overrideStart)
}
public async Task SelectStartOfWeek(ChangeEventArgs args)
{
var value = args.Value.ToString();
overrideStart = value == string.Empty ? DateTime.Today : DateTime.Parse(value);
overrideStart = await GetStartOfWeek(overrideStart);
}
private async Task<DateTime> GetStartOfWeek(DateTime date)
{
return date.AddDays(-(int)date.DayOfWeek);
}
}
显然,问题是因为它认识到overrideStart
在SelectStartOfWeek
完成之后最终具有相同的值。我试过StateHasChanged()
,但似乎没有任何效果。
在属性上使用setter的另一种方法。这在独立的EditForm
上下文中工作。
@page "/MyDate"
<h3>MyDate Editor</h3>
<EditForm EditContext="editContext">
<InputDate @bind-Value="model.MyDate"></InputDate>
</EditForm>
<input type="date" @bind-value="this.MyDate" />
@code {
private dataModel model { get; set; } = new dataModel();
private EditContext editContext;
protected override Task OnInitializedAsync()
{
this.editContext = new EditContext(model);
return base.OnInitializedAsync();
}
public class dataModel
{
public DateTime? MyDate
{
get => _myDate;
set
{
if (value != null)
{
var date = (DateTime)value;
_myDate = date.AddDays(-(int)date.DayOfWeek);
}
}
}
private DateTime? _myDate;
}
public DateTime? MyDate
{
get => _myDate;
set
{
if (value != null)
{
var date = (DateTime)value;
_myDate = date.AddDays(-(int)date.DayOfWeek);
}
}
}
private DateTime? _myDate;
}
您已经正确地确定了问题,但我认为只有一些巧妙的方法可以避免这种优化。
一种这样的方法是更改元素上的其他内容,比如@key
,它将迫使Blazor替换整个元素。
<input
@key="@toggle"
type="date"
value="@overrideStart.ToString("yyyy-MM-dd")"
@onchange="@SelectStartOfWeek" />
@code {
bool toggle;
private DateTime overrideStart = DateTime.Today;
protected override async Task OnInitializedAsync()
{
overrideStart = await GetStartOfWeek(overrideStart);
}
public async Task SelectStartOfWeek(ChangeEventArgs args)
{
var value = args.Value.ToString();
overrideStart = value == string.Empty ? DateTime.Today : DateTime.Parse(value);
overrideStart = await GetStartOfWeek(overrideStart);
toggle = !toggle;
}
private ValueTask<DateTime> GetStartOfWeek(DateTime date)
{
return ValueTask.FromResult(date.AddDays(-(int)date.DayOfWeek));
}
}