I want to perform the following. I have a ToggleSwitch whichs Toggled event handler performs some action. If this action fails I want to reset the ToggleSwitch's state to what it was.
I achieve this by doing: toggleSwitch.IsOn = !toggleSwitch.IsOn;
My problem is that this again raises the Toggled event resulting in an infinit loop if the action always fails.
Here is my complete code sample
private async void ToggleSwitch_Toggled(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
ToggleSwitch toggleSwitch = sender as ToggleSwitch;
success = dummyService.performAction(toggleSwitch.IsOn);
if (!success )
{
//raise dialog to inform user here
toggleSwitch.IsOn = !toggleSwitch.IsOn;
}
}
I know that this behavior is already implemented in different apps so it can't be too hard to achieve this.
You can do something like this detaching and reattaching your event:
if (!success )
{
toggleSwitch.Toggled -= ToggleSwitch_Toggled;
try
{
toggleSwitch.IsOn = !toggleSwitch.IsOn;
}
finally
{
toggleSwitch.Toggled += ToggleSwitch_Toggled;
}
}