Xamarin - How to trigger an animation using a MessagingCenter

185 views Asked by At

I have a ContentView that is subscribed to a MessagingCenter message from a ViewModel (In order to maintain the mvvm pattern by not coupling the view to the viewModel). When the message is received by the ContentView I wanted it to perform an animation to make a swipe view visible as follows:

MessagingCenter.Subscribe<SideMenuViewModel>(this, "IsMenuOpen", async (sender) =>
{
    if (sender.IsMenuOpen)
    {
        MainSwipeView.Open(OpenSwipeItem.RightItems);
        await SwipeContent.ScaleYTo(1, 300, Easing.SinOut);
    }
    else
    {
        MainSwipeView.Close();
        await SwipeContent.ScaleYTo(1, 300, Easing.SinOut);
    }
});

This animation is the same as the one that I have in other event listeners on the same file and it works fine. However, in the MessagingCenter the chain of execution works fine and it calls the animation method but no animation happens.

Could this potentially be a threading issue? I've tried both await and BeginInvokeOnMainThread but neither worked.

2

There are 2 answers

3
I Am The Blu On

Try doing something this, hope it may be helpful.

MessagingCenter for SEND

MessagingCenter.Send(this, "SideMenuViewModel:IsMenuOpen", IsMenuOpen);  //IsMenuOpen - is the bool value for your situation

MessagingCenter for SUBSCRIBE

MessagingCenter.Subscribe<SideMenuViewModel, bool>(this, "SideMenuViewModel:IsMenuOpen", (sender, IsMenuOpen) =>
     {
        if (IsMenuOpen)
        {
            MainSwipeView.Open(OpenSwipeItem.RightItems);
            await SwipeContent.ScaleYTo(1, 300, Easing.SinOut);
        }
        else
        {
            MainSwipeView.Close();
            await SwipeContent.ScaleYTo(1, 300, Easing.SinOut);
        }
});

Your bool value will be fetched in the IsMenuOpen parameter of subscribe. Which will have scope locally within only MessagingCenter.

Let me know if it works fine or not...

0
Leo Zhu On

await SwipeContent.ScaleYTo(1, 300, Easing.SinOut);

The ScaleTo method obtains the current Scale property value (default value of 1) for the start of the animation, and then scales from that value to its first argument,1 seems to mean no change, and you try to change it to a value that is not 1.

like:

await SwipeContent.ScaleYTo(1.5, 300, Easing.SinOut);