【发布时间】:2021-04-13 23:49:49
【问题描述】:
谁知道如何初始化一个复选框列表,其中只有 myPicketItemsStoredInDabase 项目标记为选中,所有其他项目标记为未选中?
当我尝试下面的代码示例时,所有复选框都标记为已选中。我尝试了不同的解决方案,但没有一个最终会出现一个复选框列表,其中正确的项目标记为已选中。
public class CheckboxItem
{
public Guid Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}
public class ItemFromDatabase
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Page.razor
@foreach (var item in itemsToEdit)
{
<CheckBoxItemComponent Items="@itemsToEdit" Value="@item.Name" Item="@item" />
}
@code {
private IEnumerable<ItemFromDatabase> myPickedItemsStoredInDatabase;
private IEnumerable<ItemFromDatabase> allItems;
private List<CheckboxItem> itemsToEdit;
protected override async Task OnInitializedAsync()
{
myPickedItemsStoredInDatabase = await getFromJsonAsync<ItemFromDatabase>.....
allItems= await getFromJsonAsync<ItemFromDatabase>.....
InitCheckboxItems();
}
private void InitCheckboxItems()
{
itemsToEdit = new List<CheckboxItem>();
for (int i = 0; i < allItems.Length; i++)
{
CheckboxItem item = new CheckboxItem()
{
Id = allItems[i].Id,
Name = allItems[i].Name,
Checked = false
};
if (myPickedItemsStoredInDatabase.Any(p => p.Id == item.Id))
{
item.Checked = true;
}
itemsToEdit.Add(item);
}
}
}
CheckBoxItemComponent.razor
Activate multiple checkbox in a loop using Blazor
<input type="checkbox" @bind=isChecked />@Item.Name<br />
@code
{
[Parameter]
public string Value { get; set; }
[Parameter]
public CheckboxItem Item { get; set; }
[Parameter]
public List<CheckboxItem> Items { get; set; }
private bool isChecked
{
get => Items.Any(el => el.Name == Value);
set
{
if (value)
{
if (!Items.Any(el => el.Name == Value))
Items.Add(Item);
}
else
Items.Remove(Item);
}
}
}`
【问题讨论】: