Handling Switch Control in DataGridBooleanColumn for DataGrid in MAUI
Environment
| Version | Product | Author |
|---|---|---|
| 10.1.0 | Telerik UI for .NET MAUI DataGrid | Dinko Krastev |
Description
When using a DataGridBooleanColumn with a custom CellContentTemplate that includes a Switch control, triggering the Switch does not call the SelectionChanged and CurrentCellChanged events as expected. The mouse events are handled by the Switch control. Moreover, setting the InputTransparent property of the Switch to true allows these events to be called but makes the Switch non-interactive.
Solution
To ensure that the Switch control inside the DataGridBooleanColumn can both trigger cell selection events (SelectionChanged and CurrentCellChanged) and remain interactive (toggable), follow these steps:
- Avoid setting the
InputTransparentproperty of theSwitchtotrue. This keeps theSwitchinteractive. - Use the
CellContentTemplateto include theSwitchcontrol. - Handle the
Switch.Toggledevent to manually set theCurrentCellof the DataGrid. - Opt out from using the
CellEditTemplateand prevent the default edit template from appearing by settingCanUserEdittofalse.
Below is the implementation:
var dgBooleanColumn = new DataGridBooleanColumn
{
PropertyName = "IsEnabled",
HeaderText ="Custom Bool Column",
Width = 50
};
this.dataGrid.Columns.Add(dgBooleanColumn );
var customDataTemplate= new DataTemplate(() =>
{
var tb = new Switch()
{
IsEnabled = true,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
tb.SetBinding(Switch.IsToggledProperty, "IsEnabled");
tb.Toggled += (sender, e) =>
{
var control = sender as Switch;
if (control.IsFocused)
{
var switchBooleanColumn = this.dataGrid.Columns.FirstOrDefault(x => x.HeaderText == "Custom Bool Column");
if (switchBooleanColumn != null)
{
Dispatcher.Dispatch(() =>
{
var cellInfo = new DataGridCellInfo(control.BindingContext, switchBooleanColumn);
this.dataGrid.CurrentCell = cellInfo;
});
}
}
};
return tb;
});
dgBooleanColumn .CanUserEdit = false;
dgBooleanColumn .CellContentTemplate = customDataTemplate;
This solution ensures that the Switch control is functional and interacts with the DataGrid's cell selection mechanism as intended.