ant-design-blazor/components/date-picker/DatePicker.Razor.cs
笨木头 7d9d6fc89d fix(module: form): value not change when model change (#333)
* feat(module: datepicker): support nullable type

* fix(module: cascader): displaytext did not change when bind-value change

* fix(module: form): can not change layout

* docs(module: form): add 'new model' test button

Co-authored-by: James Yeung <shunjiey@hotmail.com>
2020-07-11 23:03:13 +08:00

125 lines
3.3 KiB
C#

using System;
using Microsoft.AspNetCore.Components;
namespace AntDesign
{
public partial class DatePicker<TValue> : DatePickerBase<TValue>
{
protected override void OnInitialized()
{
base.OnInitialized();
if (Value != null)
{
GetIfNotNull(Value, notNullValue =>
{
ChangeValue(notNullValue, 0);
});
}
}
protected void OnInput(ChangeEventArgs args, int index = 0)
{
if (args == null)
{
return;
}
if (TryParseValueFromString(args.Value.ToString(), out TValue changeValue, out _))
{
Value = changeValue;
GetIfNotNull(changeValue, (notNullValue) =>
{
_pickerValues[index] = notNullValue;
});
StateHasChanged();
}
UpdateCurrentValueAsString();
}
/// <summary>
/// Get value by picker index
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public override DateTime? GetIndexValue(int index)
{
if (_pickerStatus[index]._hadSelectValue)
{
if (Value == null)
{
return null;
}
return Convert.ToDateTime(Value, this.CultureInfo);
}
else if (_defaultValues[index] != null)
{
return _defaultValues[index];
}
return null;
}
public override void ChangeValue(DateTime value, int index = 0)
{
bool result = BindConverter.TryConvertTo<TValue>(
value.ToString(CultureInfo), CultureInfo, out var dateTime);
if (result)
{
Value = dateTime;
}
_pickerStatus[index]._hadSelectValue = true;
UpdateCurrentValueAsString();
if (IsRange && !IsShowTime && Picker != DatePickerType.Time)
{
if (_pickerStatus[0]._hadSelectValue && _pickerStatus[1]._hadSelectValue)
{
Close();
}
}
else if (!IsShowTime && Picker != DatePickerType.Time)
{
Close();
}
}
protected override void OnValueChange(TValue value)
{
base.OnValueChange(value);
_pickerStatus[0]._hadSelectValue = true;
}
public override void ClearValue(int index = 0)
{
_isSetPicker = false;
CurrentValue = default;
Close();
}
private void GetIfNotNull(TValue value, Action<DateTime> notNullAction)
{
if (!_isNullable)
{
DateTime dateTime = Convert.ToDateTime(value, CultureInfo);
if (dateTime != DateTime.MinValue)
{
notNullAction?.Invoke(dateTime);
}
}
if (_isNullable && value != null)
{
notNullAction?.Invoke(Convert.ToDateTime(value, CultureInfo));
}
}
}
}