Home > other >  Add an animation to a visual element using triggers on Xamarin.Forms
Add an animation to a visual element using triggers on Xamarin.Forms

Time:04-04

I would like to add an animation to MyFrame when the user changes the current item of the carousel view. I would like to do it if it is possible using a trigger. This is my XAML:

<CarouselView ItemsSource="{Binding Items}">
   <CarouselView.ItemTemplate>
      <DataTemplate>
         <StackLayout>
            <Frame x:Name="MyFrame">
               <StackLayout>
                  <Label Text="{Binding Name}"/>
               </StackLayout>
            </Frame>
         </StackLayout>
      </DataTemplate>
   </CarouselView.ItemTemplate>

   <CarouselView.Triggers>
        <EventTrigger Event="CurrentItemChanged">
            <triggers:ScaleAction/>
        </EventTrigger>
   </CarouselView.Triggers>
</CarouselView>

Here is the trigger action:

public class ScaleAction : TriggerAction<VisualElement>
{
    protected override void Invoke(VisualElement sender)
    {
        (sender as CarouselView).ScaleTo(0.5);
    }
}

So my question is, how could I send the current frame to the trigger action?

CodePudding user response:

You already have your CarouselView in the trigger action as the sender variable. CarouselView has a CurrentItem property. You should be able to take that item and cast it to a Frame

CodePudding user response:

There is an event in CarousView called CurrentItemChangedCommand which is executed when the current item changes.use it like:

<CarouselView ItemsSource="{Binding Items}"
              CurrentItemChanged="OnCurrentItemChanged">
    ...
</CarouselView>

void OnCurrentItemChanged(object sender, CurrentItemChangedEventArgs e)
{
   //deal with the sender
}
  • Related