我正在使用 MudBlazor 创建动态表单以编辑对象。该对象有多种数据类型。我使用 @bind-Value 创建表单和加载数据没有任何问题。但是,当值更改时,只有“string”数据类型按预期工作,所有其他数据类型都不能。调查 MudBlazor 的“TextChanged”回调,我发现它是一个字符串类型,这解释了为什么只更新该数据类型。
我也尝试过使用“ValueChanged”。但是,这确实显示了数据及其元素。
有没有办法通过将“TextChanged”转换为特定数据类型来实现此目的?有什么方法可以以任何其他形式实现我正在寻找的结果吗?
@if (property.PropertyType == typeof(string))
{
var stringValue = (string)value;
<MudTextField T="string" @bind-Value="stringValue" Label="@propertyName"
TextChanged="value => property.SetValue(objectToEdit, value)"
Variant="MudBlazor.Variant.Outlined" AdornmentColor="Color.Warning"
Immediate="true" />
}
}
else if (property.PropertyType == typeof(DateTime) || property.PropertyType ==
typeof(DateTime?))
{
var dateValue = (DateTime?)(value ?? default(DateTime?));
<MudTextField T="DateTime?" @bind-Value="dateValue" Format="yyyy-MM-dd"
InputType="InputType.Date" Label="@propertyName"
TextChanged="dateValue => property.SetValue(objectToEdit, value)"
Variant="MudBlazor.Variant.Outlined"
AdornmentColor="Color.Warning" Immediate="true" />
}
else if (property.PropertyType == typeof(int?))
{
var intValueNull = (int?)value;
<MudTextField T="int?" @bind-Value="intValueNull" Label="@propertyName"
Variant="MudBlazor.Variant.Outlined"
TextChanged="intValueNull => property.SetValue(objectToEdit, value)"
AdornmentColor="Color.Warning" Immediate="true" />
}
else if (property.PropertyType == typeof(short?))
{
var shortValueNull = (short?)value;
<MudTextField T="short?" @bind-Value="shortValueNull" Label="@propertyName"
Variant="MudBlazor.Variant.Outlined"
TextChanged="shortValueNull => property.SetValue(objectToEdit, value)"
AdornmentColor="Color.Warning" Immediate="true" />
}
供将来参考以及如果有人决定使用这段代码。
解决办法是这样的:
TextChanged="intValue => {
if (!string.IsNullOrEmpty(intValue.ToString())) {
property.SetValue(objectToEdit, int.Parse(intValue));
}
}"