Switch -> EventToCommand: Detect if Toggled from user interaction or from webservices/websocket sync

MatteoPiccioniMatteoPiccioni USMember ✭✭

first of all, sorry for my english

I have a page with a number of Switch..each switch turn on/off a remote light using webservices.
To make this I used behaviors and Command in ViewModel linked to Toggled event (we call it SetOnOffSwitchCommand)

At page appearing I call a command to load the real state of each switch (we call it OnAppearingCommand),
In this command I call a w.s. and I set on or off each Switch using a IsToggled binded property
Each time I set on or off a Switch, my 'SetOnOffSwitchCommand' is called, and this is not good.
To fix this problem I add in 'SetOnOffSwitchCommand' a way to exit the command without calling the ws:
if (isBusy) then return;
In fact in my OnAppearingCommand I have a 'IsBusy' boolean used to show an ActivityIndicator.

The problem is that I use websocket too, to update the switch status while the user has the page opened.
If a websocket specific message is received, I call a third command in my viewmodel (SetOnOffFromWebServicesCommand)
The problem is that, also using the 'IsBusy' trick, when I change the state of a Switch, the SetOnOffSwitchCommand is called, and the IsBusy flag is set to false form the SetOnOffFromWebServicesCommand before the SetOnOffSwitchCommand is called.

Exist a sure way to fix my problem?


  • LandLuLandLu Member, Xamarin Team Xamurai

    If you don't want to trigger the switch's toggled command, you could use public Command(Action execute, Func<bool> canExecute);. Define Another property in your view model called canSwitchExecute and your switch's trigger command may be like:

    ToggledCommand = new Command(() =>
        // This command can only be triggered when canSwitchExecute and IsBusy are both true.
    }, () =>
        return canSwitchExecute && IsBusy;

    Then set the value to false when you are loading the data from your service:

    canSwitchExecute = false;
    // Loading...
    await Task.Delay(100);
    canSwitchExecute = true;
Sign In or Register to comment.