Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Using MudBlazor, how can I respond to checkbox changes to create a Select All checkbox for a list of checkboxes

$
0
0

I'm trying to create something like the multi-select Select control except the list of checkboxes are always visible. I've gotten pretty close using @bind-Value and @oninput, but the @oninput fires before the checkbox value has changed causing the "Select All" state to be behind by 1 selection. Is there a better way to bind these, or is it possible to just have the Select control stay open?

Last resort is using a MudTable.

https://try.mudblazor.com/snippet/mamoEUPLgPhmeROZ

<MudCheckBox  @bind-Value="@AllSelected" @oninput="OnAllSelectedChanged" Label="Select All"> @AllSelected</MudCheckBox>@foreach (var site in Sites){<MudCheckBox @bind-Value="@site.IsSelected" @oninput="CheckboxChanged" Label="@site.Name">@site.IsSelected</MudCheckBox>        }<MudTextField Label="Log" Variant="Variant.Filled" AutoGrow @bind-Value="@log"></MudTextField>@code{     public bool? AllSelected = null;    public List<Site> Sites = new List<Site>();    public string log = "";    public class Site    {        public int Id;        public string Name;        public bool IsSelected;    }    protected override async Task OnInitializedAsync()    {        Sites.Add(new Site{Id=1,Name="Site1",IsSelected=false});        Sites.Add(new Site{Id=2,Name="Site2",IsSelected=true});        Sites.Add(new Site{Id=3,Name="Site3",IsSelected=true});    }    private void OnAllSelectedChanged(ChangeEventArgs e)    {                AllSelected = (bool?)e.Value;        foreach (var site in Sites)        {            site.IsSelected = AllSelected.Value;        }        log += $"All checkbox changed {e.Value}\r\n";    }    private void CheckboxChanged(ChangeEventArgs e)    {                log += $"Checkbox changed {e.Value} ";        if (Sites.All(x => x.IsSelected))        {            AllSelected = true;            log += $"ALL\r\n";        }        else if (Sites.All(x => !x.IsSelected))        {            AllSelected = false;            log += $"NONE\r\n";        }        else        {            AllSelected = null;            log += $"SOME\r\n";        }        StateHasChanged();  //doesn't seem to work for updating AllSelected checkbox    }}    

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>