Xamarin.Forms.Switch在更新值时发送Toggled事件

asp*_*yct 5 c# events xamarin xamarin.forms

所以我还在首次亮相Xamarin.Forms.到目前为止,如果我把我遇到的一些麻烦的错误放在一边这么好.这是新人.也许你们其中一个人可以告诉我,如果我做错了什么.

基本上,我有一个Xamarin.Forms.Switch在我的界面上,我正在倾听Toggled事件的状态变化.该文档说明了这个事件:"当用户切换此Switch时引发的事件."

不幸的是,当我以编程方式更新交换机的值时,事件将触发.

var mySwitch = new Switch ();
mySwitch.Toggled += (object sender, ToggledEventArgs e) => {
    Console.WriteLine ("Switch.Toggled event sent");
};
mySwitch.IsToggled = true;
Run Code Online (Sandbox Code Playgroud)

有什么方法可以阻止事件触发/知道它不是触发事件的用户?

Bra*_*ick 5

您遇到的行为是正确的:每次IsToggled属性更改时,开关都会触发Toggled事件。

我不确定Xamarin.Forms 文档最近是否已更新,但截至今天,它是这样描述该Toggled事件的:

切换此开关时引发的事件

示例代码

以下是当用户未触发事件时阻止Toggled处理事件的示例代码Toggled

在此输入图像描述

using System;

using Xamarin.Forms;

namespace SwitchToggle
{
    public class SwitchPage : ContentPage
    {
        public SwitchPage()
        {
            var mySwitch = new Switch
            {
                IsToggled = true
            };
            mySwitch.Toggled += HandleSwitchToggledByUser;

            var toggleButton = new Button
            {
                Text = "Toggle The Switch"
            };
            toggleButton.Clicked += (sender, e) =>
            {
                mySwitch.Toggled -= HandleSwitchToggledByUser;
                mySwitch.IsToggled = !mySwitch.IsToggled;
                mySwitch.Toggled += HandleSwitchToggledByUser;
            };

            var mainLayout = new RelativeLayout();

            Func<RelativeLayout, double> getSwitchWidth = (parent) => parent.Measure(mainLayout.Width, mainLayout.Height).Request.Width;
            Func<RelativeLayout, double> getToggleButtonWidth = (parent) => parent.Measure(mainLayout.Width, mainLayout.Height).Request.Width;

            mainLayout.Children.Add(mySwitch,
                Constraint.RelativeToParent((parent) => parent.Width / 2 - getSwitchWidth(parent) / 2),
                Constraint.RelativeToParent((parent) => parent.Height / 2 - mySwitch.Height / 2)
            );
            mainLayout.Children.Add(toggleButton,
                Constraint.RelativeToParent((parent) => parent.Width / 2 - getToggleButtonWidth(parent) / 2),
                Constraint.RelativeToView(mySwitch, (parent, view) => view.Y + view.Height + 10)
            );

            Content = mainLayout;

        }

        async void HandleSwitchToggledByUser(object sender, ToggledEventArgs e)
        {
            await DisplayAlert(
                "Switch Toggled By User",
                "",
                "OK"
            );
        }
    }

    public class App : Application
    {
        public App()
        {
            MainPage = new NavigationPage(new SwitchPage());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,它是“文档准确的”,但每次我想以编程方式启动开关时都必须取消注册事件,这仍然是一件痛苦的事情。从功能的角度来看,这没有意义。 (2认同)