Xamarin Forms: Button event sequence and Command

MariusBloemhofMariusBloemhof USMember ✭✭
edited March 2018 in Xamarin.Forms

Hi,

I have a simple custom button that adds a pressed animation effect. However, I have found that it would sometimes still be busy with the animation when it fires the Command bound to this control, which results in the weird freezing artefact of the animation.

The sequence of events seems to be Pressed, Released(Command), , Clicked but because my animation runs async, the pressed is triggered while the animation still runs, the Command is invoked while the animation is still running.

To try and fix this, I have intercepted the Command, and I then invoke it myself.

        public RoundedButton() : base()
        {
            this.Pressed += AnimateButtonPress;
            this.Released += OnReleased;
        }

        private async void AnimateButtonPress(object sender, EventArgs e)
        {
            try
            {
                ButtonCommand = Command;
                Command = null;
                if (Animate &&
                    !isAnimating)
                {
                    isAnimating = true;
                    await this.ScaleTo(1.1, 70, Easing.Linear);
                    await this.ScaleTo(1, 30, Easing.BounceOut);
                    isAnimating = false;
                }
                if (ButtonCommand != null &&
                    ButtonCommand.CanExecute(CommandParameter))
                {
                    ButtonCommand.Execute(CommandParameter);
                }
            }
            finally
            {
                Command = ButtonCommand;
            }
        }

Is this a good idea? Or is there any other way of doing it

Sign In or Register to comment.