New to Telerik UI for Blazor? Download free 30-day trial

ButtonGroup Mixed Selection Mode

Environment

Product ButtonGroup for Blazor

Description

How to create a third selection mode that is a mix between Single and Multiple? How to force at least one selected ButtonGroup button?

Currently, there are two possible options for the SelectionMode in the ButtonGroup. The third mode needs to allow multiple selection and not allow deselecting the last selected item. Minimum one button needs to stay always selected.

Solution

Handle the SelectedChanged event of each ButtonGroupToggleButton, and when you deselect a button, check if it was the last selected.

<TelerikButtonGroup SelectionMode="@ButtonGroupSelectionMode.Multiple">
    <ButtonGroupToggleButton Selected="@FirstSelected" SelectedChanged="@((bool currState) => SelectedChangedHandler(currState, 1))">First</ButtonGroupToggleButton>
    <ButtonGroupToggleButton Selected="@SecondSelected" SelectedChanged="@((bool currState) => SelectedChangedHandler(currState, 2))">Second</ButtonGroupToggleButton>
    <ButtonGroupToggleButton Selected="@ThirdSelected" SelectedChanged="@((bool currState) => SelectedChangedHandler(currState, 3))">Third</ButtonGroupToggleButton>
</TelerikButtonGroup>

@code {
    List<int> selectedButtons { get; set; } = new List<int>();

    bool FirstSelected { get; set; }
    bool SecondSelected { get; set; }
    bool ThirdSelected { get; set; }

    void SelectedChangedHandler(bool currState, int btnIndex)
    {
        if (currState && !(selectedButtons.Contains(btnIndex)))
        {
            selectedButtons.Add(btnIndex);
        }
        else if (!currState && selectedButtons.Count > 1)
        {
            selectedButtons.Remove(btnIndex);
        }

        FirstSelected = selectedButtons.Contains(1);
        SecondSelected = selectedButtons.Contains(2);
        ThirdSelected = selectedButtons.Contains(3);
    }
}

See Also

In this article