英文:
Structure references to elements in loops in Blazor
问题
当单击按钮时,要识别正确的 "MudOverlay" 可以采用以下方法。你的想法使用字典是一个有效的方法,但也可以使用索引来实现,具体取决于你的数据结构和偏好。
使用字典的方法:
@code {
Dictionary<int, bool> isThinkingDictionary = new Dictionary<int, bool>();
}
@foreach (var item in items)
{
<MudOverlay Visible="isThinkingDictionary.ContainsKey(item.Id) ? isThinkingDictionary[item.Id] : false" DarkBackground="true">
<MudProgressCircular Indeterminate="true" />
</MudOverlay>
<MudTextField @bind-Value="item.Text"></MudTextField>
<MudButton OnClick="@(async () => await SaveItem(item, item.Id))">Start</MudButton>
}
async Task SaveItem(Item item, int itemId)
{
// Perform your save operation here
isThinkingDictionary[itemId] = true;
// After saving, you can set isThinking to false when the operation is complete.
// isThinkingDictionary[itemId] = false;
}
使用索引的方法:
@foreach (var item in items)
{
int itemIndex = items.IndexOf(item);
<MudOverlay Visible="isThinking == itemIndex" DarkBackground="true">
<MudProgressCircular Indeterminate="true" />
</MudOverlay>
<MudTextField @bind-Value="item.Text"></MudTextField>
<MudButton OnClick="@(async () => await SaveItem(itemIndex))">Start</MudButton>
}
async Task SaveItem(int itemIndex)
{
// Perform your save operation here
isThinking = itemIndex;
// After saving, you can reset isThinking when the operation is complete.
// isThinking = -1;
}
这两种方法都可以用来标识正确的 "MudOverlay",你可以根据自己的项目结构和需求选择其中一种方法。希望这些方法对你有所帮助。
英文:
Imagine I have an input field and a button and when I click the button, I want an overlay to appear. Easy. (this code is meant to illustrate the situation and may not compile)
<MudOverlay Visible="isThinking" DarkBackground="true">
<MudProgressCircular Indeterminate="true" />
</MudOverlay>
<MudTextField></MudTextField>
<MudButton OnClick="SaveItem">Start</MudButton>
(inside the "SaveItem" function I will set "isThinking" to "true")
Now imagine the same thing inside a loop of items.
@foreach (var item in items)
{
<MudOverlay Visible="isThinking" DarkBackground="true">
<MudProgressCircular Indeterminate="true" />
</MudOverlay>
<MudTextField @bind-Value="item.Text"></MudTextField>
<MudButton OnClick="@(async () => await SaveItem(item))">Start</MudButton>
}
My question is how should I identify the correct "MudOverlay" when the button is clicked? I cannot just use isThinking
because it would activate the MudOverlay on every item.
My best idea so far is to put a Dictionary<string, bool> isThinkingList
where I keep the
isThinking
status for each loop and then I use Visible="@(isThinkingList[item.Id])"
I highly doubt the Dictionary approach is the established best practice, hence this question. Hoping for your help. Thank you.
答案1
得分: 1
最简单的方法是使用 item.IsThinking
。
当 item
是一个 ViewModel 时,就没有问题。否则,将其变成一个 ViewModel。
英文:
The easiest way is to have item.IsThinking
.
When item
is a ViewModel then there is no problem. Otherwise, make (it) a ViewModel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论