The following code snippet does exactly what I expect, which is to provide a list of 3 items that expands to show the numeral for the written number when clicked. My question is whether a Dictionary is the proper way to track the state?
Do I really have to maintain a copy of the state on this page, or is there a way to bind the click event to directly modify the value of the property on the component rather than a local copy of the status which is bound to the components value?
<div class="row">
<div class="col">
<ul>
@if(Items != null)
{
foreach(var kvp in Items)
{
<li @key="kvp.Key" @onclick="@(e => Toggle(kvp.Key))">@kvp.Key <CollapsibleRow @bind-Expanded="expanded[kvp.Key]">@kvp.Value</CollapsibleRow></li>
}
}
</ul>
</div>
</div>
@code {
Dictionary<string, bool> expanded = Items.Select(o => new KeyValuePair<string, bool>(o.Key, false)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
void Toggle(string key)
{
expanded[key] = !expanded[key];
}
static Dictionary<string, string> Items = new()
{
{ "One", "1" },
{ "Two", "2" },
{ "Three", "3" }
};
}