Events in .NET MAUI Switch

This section provides information about the events available in the .NET MAUI Switch control.

StateChanged event

The StateChanged event occurs when the value or state of IsOn property is changed by tapping the .NET MAUI Switch button or setting a value to IsOn property. The SwitchStateChangedEventArgs provides the following properties:

  • NewValue : Gets the current value of the .NET MAUI Switch control.
  • OldValue : Gets the previous value of the .NET MAUI Switch control.
<syncfusion:SfSwitch StateChanged="SfSwitch_StateChanged"/>
SfSwitch sfSwitch = new SfSwitch();
sfSwitch.StateChanged+= SfSwitch_StateChanged;
this.Content = sfSwitch;
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");
}

SwitchStateChangedEventArgs

StateChanging event

The StateChanging event occurs when the state of IsOn property is about to change in the .NET MAUI Switch control. The SwitchStateChangingEventArgs provides the following properties:

  • NewValue : Gets the current value of the .NET MAUI Switch control.
  • OldValue : Gets the previous value of the .NET MAUI Switch control.
  • Cancel : Gets or sets a value indicating whether the event should be canceled.
<syncfusion:SfSwitch StateChanging="SfSwitch_StateChanging"/>
SfSwitch sfSwitch = new SfSwitch();
sfSwitch.StateChanging += SfSwitch_StateChanging;
this.Content = sfSwitch;
private void SfSwitch_StateChanging(object sender, SwitchStateChangingEventArgs e)
{
    // Access the new and old values
    bool? newValue = e.NewValue;
    bool? oldValue = e.OldValue;

    // Cancel the event if needed
    if (newValue == null)
    {
        e.Cancel = true;
    }
}