每当导航到该页面时,Xamarin 表单都会自动触发 Switch Toggled 事件 [英] Xamarin forms Switch Toggled event fires automatically whenever navigate to that page

查看:35
本文介绍了每当导航到该页面时,Xamarin 表单都会自动触发 Switch Toggled 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

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.

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

Followed prism MVVM, EventToCommandBehavior I should follow all these.

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

Help me with the sample code would be greatful.

推荐答案

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

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

恐怕没有办法实现它.

首先,查看源码开关代码 .

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

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

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

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

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 .

这篇关于每当导航到该页面时,Xamarin 表单都会自动触发 Switch Toggled 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆