@ZhiLv 的代码运行良好,但如果您想要一个预填充的动态选择值,它将变得更加困难。
我花了很多时间试图让这个工作MatSelectValue
没有运气。
https://www.matblazor.com/SelectValue
我最终使用了一个简单MatSelect
的属性来调用我的onchange event
方法。这是我让选择列表正确预填充的唯一方法。
具有可为空的 int 的示例,但您也可以更改为字符串、guid 等。
https://www.matblazor.com/Select#MatSelectGuid
@inject StateContainer StateContainer
<MatSelect Label="Choose threat" @bind-Value="@SelectThreatId" Outlined="true" FullWidth="true">
@foreach (var item in selectThreats)
{
<MatOption TValue="int?" Value="@item.Id">@item.Threat</MatOption>
}
</MatSelect>
@code
{
[Parameter]
public ThreatAndCountermeasureDto ThreatAndCountermeasureDto { get; set; }
List<ThreatDto> selectThreats = new List<ThreatDto>();
ThreatDto selectedThreat = null;
private int? threatId = null;
public int? SelectThreatId
{
get { return threatId; }
set
{
threatId = value;
SelectThreatValueChanged(value);
}
}
private void SelectThreatValueChanged(int? id)
{
selectedThreat = StateContainer.Threats.Single(x => x.Id == id);
}
protected override void OnInitialized()
{
base.OnInitialized();
StateContainer.OnChange += StateHasChanged;
SelectThreatId = ThreatAndCountermeasureDto.Threat.Id;
selectThreats = StateContainer.Threats.ToList();
}
...
来源:
https://github.com/SamProf/MatBlazor/issues/498