Hello,
Based on your logic that you want to achieve. As above comment said, this issue is related to the Clicked event in your custom control. So I do following steps.
Step 1 I delete Clicked += (sender, args) => IsToggled ^= true;
line in your ToggleButto's construstor.
Step 2 I add binding IsToggled="{Binding StartStopON}"
property in <controls:ToggleButton>
tag like following code.
<controls:ToggleButton Command="{Binding StartStopCommand}" IsToggled="{Binding StartStopON}" WidthRequest="120" Margin="10,10,10,10">
Step 3 I add the StartStopON property and extend the BaseViewModel.cs for properties change at runtime. Here is an article about MVVM in the Xamarin, you can refer to it. Here is my viewmodel and baseViewmodel. you can make a test.
public class MyViewModel:BaseViewModel
{
private bool startStopON;
public bool StartStopON
{
get { return startStopON; }
set
{
if (startStopON == value)
return;
startStopON = value;
OnPropertyChanged();
}
}
private async Task ActivateStartStopAsync()
{
if (this.StartStopON == false)
{
// Do something
this.StartStopON = true;
}
else
{
var result = await App.Current.MainPage.DisplayAlert("About to be shut down", "Are you sure you want to turn it off?", "OK", "Cancel");
if (result)
{
// Do something
this.StartStopON = false;
}
}
}
public ICommand StartStopCommand { get; }
public MyViewModel()
{
this.StartStopCommand = new Command(async () => await ActivateStartStopAsync());
}
}
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.