Creating a Mixed Selection Mode in the ButtonGroup
Environment
Product | ButtonGroup for Blazor |
Description
How can I create a third selection mode that is a mix between the Single
and Multiple
option? How can I force at least one selected ButtonGroup button?
Solution
Currently, the ButtonGroup SelectionMode
supports the two Single
and Multiple
options.
To create a third, multiple selection mode, prevent the deselection of the last selected item, and enable at least one button to always stay selected, handle the SelectedChanged
event of each ButtonGroupToggleButton
. 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);
}
}