Search code examples
xamarinxamarin.formsxamarin.androidxamarin.ios

How to know which indicator you are on with CarouselView in Xamarin Forms?


I a using the CarouselView and I can successfully load in items! Yey, so far so good. But now when i reach the 2nd item, I try to do a specific function that will only happen in the 2nd index.

Right now i seem to have figured out when im on the 2nd page al though the log is writing a lot of things in the log, but when i transition to the 3rd page, or back to the 1st page, i have lost count (programmatically) of where I am.

   <CarouselView BackgroundColor="Transparent"
                          HorizontalScrollBarVisibility="Never"
                          IndicatorView="indicatorView"
                          VerticalOptions="CenterAndExpand"
                          Margin="25,0"
                          Scrolled="CarouselView_Scrolled"
                          ItemsSource="{Binding BindingContext.Intro, Source={x:Reference ParentView}}">
                <CarouselView.ItemsLayout>
                    <LinearItemsLayout Orientation="Horizontal"
                                       SnapPointsAlignment="Center" 
                                       SnapPointsType="MandatorySingle"/>
                </CarouselView.ItemsLayout>
                <CarouselView.ItemTemplate>
                    <DataTemplate>
                                <Label Text="{Binding Text}"
                                       FontSize="Large"
                                       HorizontalTextAlignment="Start"
                                       FontFamily="Helvetica Neue"
                                       TextColor="DimGray"
                                       FontAttributes="None" />

                        </AbsoluteLayout>
                    </DataTemplate>
                </CarouselView.ItemTemplate>
            </CarouselView>  

Code behind:

    async void CarouselView_Scrolled(System.Object sender, Xamarin.Forms.ItemsViewScrolledEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine(e.CenterItemIndex);

        if (e.CenterItemIndex == 1)
        {
            if (Transitioning == false)
            {
                Transitioning = true;
                await ParentView.ColorTo(Color.White, Color.FromHex("#161825"), c =>
                {
                    ParentView.BackgroundColor = c;
                    Transitioning = false;
                }, 500);
            }
        }
        else
        {
            Transitioning = true;
            await ParentView.ColorTo(Color.FromHex("#161825"), Color.White, c => ParentView.BackgroundColor = c, 500);
            Transitioning = false;
        }
    }

What logic do i need to add in my frontend to successfully monitor if im on page 2?


Solution

  • ItemsViewScrolledEventArgs has a CenterItemIndex property that tells you which item is in the center view

    or you could use the CurrentItemChanged event