每当导航到该页面时,Xamarin 表单都会自动触发 Switch Toggled 事件

问题描述

我在集合视图中使用 Xamarin 表单切换,如下所示。

  <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>

由于设置了 IsToggled Binding 属性,每当我导航到该页面时,都会自动触发 Switch 的 Toggled 事件。当用户没有手动触发时,有没有办法限制 Switch Toggled 事件?

为了更清楚,我附上了我的 sample here

遵循prism MVVM、EventToCommandBehavior 我应该遵循所有这些。

帮助我提供示例代码会很棒。

解决方法

。当用户没有手动触发时,有没有办法限制 Switch Toggled 事件?

恐怕没有办法实现它。

首先,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);

很明显,如果 Toggled 属性发生变化,IsToggled 事件将触发。

换句话说,无论我们手动切换开关还是以编程方式更改IsToggledToggled 将被触发,然后 EventToCommandBehavior 将在此之后工作。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...