Search code examples
xamarin.formsxamarin.forms.carouselview

Xamarin Forms CarouselView Loop Binding Doesn't work


I have a collection bound to my CarouselView and I want to make the Loop property of the CarouselView to be true only when there is more than 1 element in the collection. This should be very easy but I don't know why it isn't working

<CarouselView ItemsSource="{Binding FoodCards}" Loop="{Binding IsLooping}">

and in my ViewModel I have a command that's executed when I press a certain button to show only one element and set IsLooping to False

IsLooping = FoodCards.Count > 1;

Can this effect be achieved? Or we cannot change Loop during runtime?

EDIT:

The workaround from the answers below works if I don't change the collection dimensions. Right now I have a collection of 3 elements bound to the CarouselView and I also have a button with a command bound to it. The code from the command is :

void OnChangeLoop(){
            Items.Clear();
            Items.Add("item1");
            Items.Add("item2");
            Loop = !Loop;
        }

and in the code behind I have the workaround with the PropertyChanged. And when I press the button I get java.Lang.IllegalArgumentException: 'Invalid target position


Solution

  • This is a known bug, you can follow the progress on https://github.com/xamarin/Xamarin.Forms/issues/13706

    Workaround (adapted from the linked issue)

    Code-behind

    YourPage()       //Constructor
    {
          InitializeComponent();
          BindingContext = new YourViewModel();
          (BindingContext as YourViewModel).PropertyChanged += Vm_PropertyChanged;
    }
    
    void Vm_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(YourViewModel.IsLooping))
        {
            carousel.Loop = ((YourViewModel)BindingContext).IsLooping;
        }
    }