vendredi 1 décembre 2023

MudBlazor checkboxes in tables being independent from one another

I want the user to be able to check only one Element at a time. If they check another element then that becomes checked any the others are false. I'm using MudBlazor and I tried to control this via a method but I've failed horribly.

<MudTable T="Element" Items="@Elements" Hover="true">
    <HeaderContent>
        <MudTh>checkbox</MudTh>
        <MudTh>Nr</MudTh>
        <MudTh>Name</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="checkbox">
            <MudCheckBox Value="@context.Checked" T="bool" CheckedChanged="CheckedChanged" Color="Color.Warning" CheckedIcon="@Icons.Material.Filled.PersonPinCircle" UncheckedIcon="@Icons.Material.Outlined.PersonPinCircle"></MudCheckBox>
        </MudTd>
        <MudTd DataLabel="Nr">@context.Number</MudTd>
        <MudTd DataLabel="Name">@context.Name</MudTd>
    </RowTemplate>
    <PagerContent>
        <MudTablePager PageSizeOptions="new int[]{50, 100}" />
    </PagerContent>
</MudTable>



@code {
    private IEnumerable<Element> Elements = new List<Element>()
    {
        new Element("helium", 1),
        new Element("borium", 45),
        new Element("argon", 346),
        new Element("oxygen", 51),
        new Element("radium", 467),
    };

    protected void CheckedChanged(object sender, EventArgs e)
    {
        // Set every other elements checked to false
        foreach (var item in Elements)
        {
            item.Checked = false;
        }   

        // set this elements checked value to what is is not
        CheckBox3 = !CheckBox3;
    }

    public class Element
    {
        public string Name { get; set; }
        public int Number { get; set; }
        public bool Checked { get; set; }

        public Element(string name, int number)
        {
            Name = name;
            Number = number;
            Checked = false;
        }
    }
}



Aucun commentaire:

Enregistrer un commentaire