Events in .NET MAUI Switch

24 Jul 20263 minutes to read

The .NET MAUI Switch control exposes the following events that are raised when the IsOn property changes.

Prerequisites

Before using the SfSwitch, ensure the following NuGet package is installed in your .NET MAUI project:

  • Syncfusion.Maui.Buttons

For a step-by-step setup, refer to the Getting Started documentation.

StateChanged

The StateChanged event is raised after the state of the IsOn property changes. The change can be triggered by tapping the .NET MAUI Switch or by setting a value to the IsOn property programmatically. The SwitchStateChangedEventArgs provides the following properties:

  • NewValue: Gets the new value of the Switch after the state has changed.
  • OldValue: Gets the previous value of the Switch before the state changed.
<syncfusion:SfSwitch x:Name="sfSwitch"
                     StateChanged="SfSwitch_StateChanged"/>
SfSwitch sfSwitch = new SfSwitch();
sfSwitch.StateChanged += SfSwitch_StateChanged;
this.Content = sfSwitch;

The StateChanged event can be handled in C# as follows:

private async void SfSwitch_StateChanged(object sender, SwitchStateChangedEventArgs e)
{
    // Access the new and old values
    bool? newValue = e.NewValue;
    bool? oldValue = e.OldValue;

    await DisplayAlert("Alert", "Switch State Changed", "Close");
}

StateChanged event

StateChanging

The StateChanging event is raised before the state of the IsOn property changes. Set the Cancel property to true to prevent the change from being applied. The SwitchStateChangingEventArgs provides the following properties:

  • NewValue: Gets the value that the Switch is about to change to.
  • OldValue: Gets the current value of the Switch before the change.
  • Cancel: Gets or sets a bool value indicating whether the state change should be canceled. The default is false.
<syncfusion:SfSwitch x:Name="sfSwitch"
                     StateChanging="SfSwitch_StateChanging"/>
SfSwitch sfSwitch = new SfSwitch();
sfSwitch.StateChanging += SfSwitch_StateChanging;
this.Content = sfSwitch;

The StateChanging event can be handled in C# as follows. The following example prevents the Switch from changing to the Indeterminate state:

private void SfSwitch_StateChanging(object sender, SwitchStateChangingEventArgs e)
{
    // Access the new and old values
    bool? newValue = e.NewValue;
    bool? oldValue = e.OldValue;

    // Cancel the state change if the new value is null (Indeterminate)
    if (newValue == null)
    {
        e.Cancel = true;
    }
}

See Also