Stop and reset video when carousal swiped – Xamarin.forms

We can use BindingContextChanged and PositionChanged Events.

<CarouselView ItemsSource="{Binding }" PositionChanged="carouselView_PositionChanged">    
        <CarouselView.ItemTemplate>    
            <DataTemplate>                       
                <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"        >    
    
                 <MediaElement AutoPlay="True" Aspect="AspectFill"
                  Source="{Binding Video}" BindingContextChanged="MediaElement_BindingContextChanged" />  
                </StackLayout>    
            </DataTemplate>    
        </CarouselView.ItemTemplate>    
    </CarouselView>

In Code Behind

List<MediaElement> mediaElements = new List<MediaElement>();

private void MediaElement_BindingContextChanged(object sender, EventArgs e)
        {
            var element = sender as MediaElement;
            mediaElements.Add(element);
        }

        private void carouselView_PositionChanged(object sender, PositionChangedEventArgs e)
        {
            mediaElements[e.PreviousPosition].Stop();
        }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top