我想为Blazor写一个自定义的下拉列表组件,部分原因是现有的InputSelect组件不绑定到除字符串和枚举类型之外的任何内容。这对我来说还不够好,因为我的模型具有要绑定到下拉列表的int和可为null的int类型属性。到目前为止,我有这个:
@using System.Globalization
@typeparam TValue
@typeparam TData
@inherits InputBase<TValue>
<select id="@Id" @bind="CurrentValueAsString" class="f-select js-form-field">
@if (!string.IsNullOrWhiteSpace(OptionLabel) || Value == null)
{
<option value="">@(OptionLabel ?? "-- SELECT --")</option>
}
@foreach (var item in Data)
{
<option value="@GetPropertyValue(item, ValueFieldName)">@GetPropertyValue(item, TextFieldName)</option>
}
</select>
<span>Component Value is: @Value</span>
@code {
[Parameter]
public string Id { get; set; }
[Parameter]
public IEnumerable<TData> Data { get; set; } = new List<TData>();
[Parameter]
public string ValueFieldName { get; set; }
[Parameter]
public string TextFieldName { get; set; }
[Parameter]
public string OptionLabel { get; set; }
private Type ValueType => IsValueTypeNullable() ? Nullable.GetUnderlyingType(typeof(TValue)) : typeof(TValue);
protected override void OnInitialized()
{
base.OnInitialized();
ValidateInitialization();
}
private void ValidateInitialization()
{
if (string.IsNullOrWhiteSpace(ValueFieldName))
{
throw new ArgumentNullException(nameof(ValueFieldName), $"Parameter {nameof(ValueFieldName)} is required.");
}
if (string.IsNullOrWhiteSpace(TextFieldName))
{
throw new ArgumentNullException(nameof(TextFieldName), $"Parameter {nameof(TextFieldName)} is required.");
}
if (!HasProperty(ValueFieldName))
{
throw new Exception($"Data type {typeof(TData)} does not have a property called {ValueFieldName}.");
}
if (!HasProperty(TextFieldName))
{
throw new Exception($"Data type {typeof(TData)} does not have a property called {TextFieldName}.");
}
}
protected override bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage)
{
validationErrorMessage = null;
if (ValueType == typeof(string))
{
result = (TValue)(object)value;
return true;
}
if (ValueType == typeof(int))
{
if (string.IsNullOrWhiteSpace(value))
{
result = default;
}
else
{
if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedValue))
{
result = (TValue)(object)parsedValue;
}
else
{
result = default;
validationErrorMessage = $"Specified value cannot be converted to type {typeof(TValue)}";
return false;
}
}
return true;
}
if (ValueType == typeof(Guid))
{
validationErrorMessage = null;
if (string.IsNullOrWhiteSpace(value))
{
result = default;
}
else
{
if (Guid.TryParse(value, out var parsedValue))
{
result = (TValue)(object)parsedValue;
}
else
{
result = default;
validationErrorMessage = $"Specified value cannot be converted to type {typeof(TValue)}";
return false;
}
}
return true;
}
throw new InvalidOperationException($"{GetType()} does not support the type '{typeof(TValue)}'. Supported types are string, int and Guid.");
}
private string GetPropertyValue(TData source, string propertyName)
{
return source.GetType().GetProperty(propertyName)?.GetValue(source, null).ToString();
}
private bool HasProperty(string propertyName)
{
return typeof(TData).GetProperty(propertyName) != null;
}
private bool IsValueTypeNullable()
{
return Nullable.GetUnderlyingType(typeof(TValue)) != null;
}
}
在父组件中,我可以这样使用它:
<DropDownList Id="@nameof(Model.SelectedYear)"
@bind-Value="Model.SelectedYear"
Data="Model.Years"
ValueFieldName="@nameof(Year.Id)"
TextFieldName="@nameof(Year.YearName)">
</DropDownList>
这很好用,模型绑定到下拉列表,并且当下拉列表值更改时,其值在父模型上也更改了。但是,我现在想在我的父项上捕获此值更改事件并执行一些自定义逻辑,主要是根据所选年份加载一些其他数据。我的猜测是我需要自定义EventCallback,但是我尝试的所有操作都会导致某种生成或运行时错误。看来,如果我的组件是从InputBase继承的,那么我只能做些限制。
谁能告诉我如何从父组件的子组件中捕获值变化?
答案 0 :(得分:3)
我的猜测是我需要一个自定义EventCallback
您确实需要一个EventCallback
,但事实是,您已经有一个,只是看不到。
要使用@bind-Value
,您需要两个参数T Value
和EventCallback<T> ValueChanged
。
当您传递@bind-Foo
时,blazor会设置这两个参数Foo
和FooChanged
,在FooChanged
中,它将简单地将新值设置为Foo
因此,当您执行@bind-Foo="Bar"
时,blazor要做的就是传递这两个参数
Foo="@Bar"
FooChanged="@(newValue => Bar = newValue)"
因此,在您的情况下,您需要做的是传递自己的ValueChanged
函数,该函数在Value
中设置新值,还可以做一些您想做的事情。
<DropDownList Id="@nameof(Model.SelectedYear)"
Value="Model.SelectedYear"
ValueChanged="@((TYPE_OF_VALUE newValue) => HandleValueChanged(newValue))"
Data="Model.Years"
ValueFieldName="@nameof(Year.Id)"
TextFieldName="@nameof(Year.YearName)">
</DropDownList>
@code
{
void HandleValueChanged(TYPE_OF_VALUE newValue)
{
// do what you want to do
// set the newValue if you want
Model.SelectedYear = newValue;
}
}
在TYPE_OF_VALUE
中,您只需将其替换为Model.SelectedYear
类型即可。
您可以在docs中查看此说明。
由于要使用可为空的类型,因此还需要传递FooExpression
,在您的情况下为Expression<Func<T>> ValueExpression
。
<DropDownList Id="@nameof(Model.SelectedYear)"
Value="Model.SelectedYear"
ValueChanged="@((TYPE_OF_VALUE newValue) => HandleValueChanged(newValue))"
ValueExpression="@(() => Model.SelectedYear)"
Data="Model.Years"
ValueFieldName="@nameof(Year.Id)"
TextFieldName="@nameof(Year.YearName)">
</DropDownList>