0

I am using Xamarin forms switch inside collection view like the below.

  <CollectionView ItemsSource="{Binding SwitchStatus}">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout>
                            <StackLayout HeightRequest="100" Orientation="Horizontal" HorizontalOptions="CenterAndExpand" Spacing="30">
                                <Switch x:Name="mySwitch" IsToggled="{Binding State}"> 
                                    <Switch.Behaviors>
                                        <prism:EventToCommandBehavior EventName="Toggled" CommandParameter="{Binding .}" Command="{Binding BindingContext.UpdateCommand,Source={x:Reference myPage}}"/>
                                    </Switch.Behaviors>
                                </Switch>
                            </StackLayout>
                        </StackLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>

            </CollectionView>

Toggled event of the Switch getting fired automatically whenever I navigate to that page because of IsToggled Binding property set. Is there any way to restrict Switch Toggled event when the user not manually triggered?

To be more clear, I have attached my sample here.

Followed prism MVVM, EventToCommandBehavior I should follow all these.

Help me with the sample code would be greatful.

Jay
  • 65
  • 8

1 Answers1

1

. Is there any way to restrict Switch Toggled event when the user not manually triggered?

I'm afraid there is no method to achieve it .

First , Check the source code of Switch .

public static readonly BindableProperty IsToggledProperty = BindableProperty.Create(nameof(IsToggled), typeof(bool), typeof(Switch), false, propertyChanged: (bindable, oldValue, newValue) =>
        {
            ((Switch)bindable).Toggled?.Invoke(bindable, new ToggledEventArgs((bool)newValue));
            ((Switch)bindable).ChangeVisualState();
        }, defaultBindingMode: BindingMode.TwoWay);

It is clear that Toggled event would trigger if the IsToggled property changes .

In other word ,no matter we toggle the switch manually or changes IsToggled programmatically , Toggled will be triggerd , and then EventToCommandBehavior will works after that .

ColeX
  • 14,062
  • 5
  • 43
  • 240