0

我在集合视图中使用 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 的切换事件就会自动触发。当用户未手动触发时,有什么方法可以限制 Switch Toggled 事件?

为了更清楚,我在这里附上了我的样本

遵循棱镜 MVVM,EventToCommandBehavior 我应该遵循所有这些。

帮助我提供示例代码将非常有用。

4

1 回答 1

1

. 当用户未手动触发时,有什么方法可以限制 Switch Toggled 事件?

恐怕没有办法实现它。

首先,查看 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

换句话说,无论我们手动拨动开关还是以IsToggled编程方式更改, Toggled都会被触发,然后EventToCommandBehavior才会起作用。

于 2021-04-17T06:20:43.033 回答