Changing CarouselView's ItemsSource and Position from code not working

I have a CarouselView that is bound (ItemSource) to a list. That list can point to two different lists. When I change the List the ItemSource is bound too, I also need to set the Position of the CarouselView to 0.

I can achieve both of these independently, but If I try to do both one after the other, then only the ItemSource change persists, the position remains unchanged.

Here is the Xaml:

<StackLayout Orientation="Vertical">
    <StackLayout Orientation="Horizontal">
        <Label Text="First List" FontSize="Large"/>
        <Switch IsToggled="{Binding IsFirstList}"/>
        <Label Text="Second List" FontSize="Large"/>
        ItemsSource="{Binding TheList}" 
        ItemTemplate="{StaticResource ExampleTemplate}"
        Position="{Binding TheListIndex}"/>

Here is the cs:

List<Stuff> _firstList;
List<Stuff> _secondList
public List<Stuff> TheList
    get => IsFirstList ? _firstList : _secondList;

int _theListIndex = 0;
public int TheListIndex
    get => _theListIndex;
    set => SetProperty(ref _theListIndex, value);

bool _isFirstList = false;
public bool IsFirstList
    get => _isFirstList;
        SetProperty(ref _isFirstList, value);
        TheListIndex = 0;

I simplified the code above by renaming variables and methods.

Leaving the above code as is, when I toggle the switch, the change to the TheList takes affect as expected, but the Position of the CarouselView remains where it was, thus the TheListIndex call ultimately doesn't persist. When I place breakpoints in the TheListIndex setter and getter, they are both hit twice in the order and with the values of: setter value 0, getter value 0, then setter with the old value, and finally the getter with the old value.

If I remove the RaisePropertyChanged line, then calling TheListIndex = 0 properly sets the CarouselView's position to 0.

I'd appreciate any help. Thanks!

Also, It would be event better if I could simplify all of this by having the CarouselView's Position reset to 0 when the Switch changes directly configured from the Xaml.

Sign In or Register to comment.