我有一个名为SearchSelect的华丽的TypeAhead组件。下面是代码:
@using _3T.OPAMS.Entities.Models
@inject ISearchService SService
<BlazoredTypeahead SearchMethod="SearchItems"
TValue="SearchResult"
TItem="SearchResult"
Value="SelectedItem"
ValueChanged="@((SearchResult i) =>TriggerCallback(i))"
ValueExpression="@(()=> SelectedItem)"
Debounce="500" class="form-control"
Placeholder="@($"Search for {SelectType.Humanize()}...")">
<SelectedTemplate Context="item">
<b class="text-bold me-2">@item.Name</b>
</SelectedTemplate>
<ResultTemplate Context="item">
<div class="d-flex text-sm">
<div>
<b class="text-bold">@item.Name</b><br />
@item.Description
</div>
</div>
</ResultTemplate>
<NotFoundTemplate Context="itemtype">
Sorry, there weren't any search results.
</NotFoundTemplate>
</BlazoredTypeahead>
<h4>@SelectedItem?.Name</h4>
@code {
private SearchResult SelectedItem;
[Parameter] public SSelectType SelectType { get; set; }
[Parameter] public EventCallback<SearchResult> OnChange { get; set; }
[Parameter] public EventCallback<int> OnChangeId { get; set; }
public void SetValue(SearchResult sr)
{
SelectedItem = sr;
}
private async Task TriggerCallback(SearchResult item)
{
await OnChange.InvokeAsync(item);
if (item != null)
{ await OnChangeId.InvokeAsync(item.Id); }
SelectedItem = item;
}
private async Task<IEnumerable<SearchResult>> SearchItems(string searchText)
{
switch (SelectType)
{
case SSelectType.Collection:
return (await SService.Collections(searchText));
case SSelectType.MainMaterial:
return (await SService.MainMaterials(searchText));
case SSelectType.SecondaryMaterial:
return (await SService.MainMaterials(searchText));
case SSelectType.Finishing:
return (await SService.Finishes(searchText));
case SSelectType.ItemType:
return (await SService.ItemTypes(searchText));
default:
return (await SService.All(searchText));
}
}
}
我这样使用它:
<div class="col-md-4 form-group">
<label>@Localize["Collection"]</label>
<SearchSelect @key="1" @ref="CSelect" OnChangeId="(id)=> Entity.CollectionId=id" SelectType="SSelectType.Collection" />
<ValidationMessage For="@(() => Entity.CollectionId)" />
</div>
然后在代码中我有一个引用。
protected SearchSelect CSelect { get; set; }
然后在oninitializedasync Method中,我设置:
if (Entity.Collection != null)
{
CSelect.SetValue(new SearchResult(Entity.Collection));
}
但是,问题是值没有被设置。任何意见都会很有帮助。谢谢。
用OnAfterRender代替OnInitialized/OnInitializedAsync;
组件的引用在on初始化时不可用,你不能访问它们。
protected override Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
if (Entity.Collection != null)
{
CSelect.SetValue(new SearchResult(Entity.Collection));
}
}
}