Home > Back-end >  ObservableCollection and ListView strange behavior under iOS
ObservableCollection and ListView strange behavior under iOS

Time:01-17

I bind an ObservableCollection called Messages to a ListView in Xamarin Forms. I populate the collection as follows:

for (int i=0; i<5; i  ) {
    Messages.Insert(0, 
                new Message() {
                   Text = "M" i
                });
}

This works as expected under Android, and my ListView shows 5 messages with texts 'M0',..,'M4'. However, under iOS I will get the 5 messages, but each of them shows the text 'M4'.

When I walk this in the debugger, it shows the correct text for each messages ('M0',..,'M4'). So the data is correct, but the ListView shows the text of the last message in each message, rather than the correct text.

Not sure what's happening here. Any ideas/workarounds?

Thanks!

EDIT: See my own answer/solution below.

CodePudding user response:

1.Based on your code I wrote an example that will display correctly on iOS for your reference:

Here is the xaml code:

<StackLayout>
    <ListView x:Name="mylist">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Label Text="{Binding Text}"></Label>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

Here is the background code:

public partial class MainPage : ContentPage
{
    ObservableCollection<Message> observableCollection { get; set; } = new ObservableCollection<Message>();
    public MainPage()
    {
        InitializeComponent();
        for (int i = 0; i < 5; i  )
        {
           
            observableCollection.Insert(0, new Message() {Text = "m"   i });
        }
        mylist.ItemsSource = observableCollection;
    }
}

2.According to your code, the index position you insert every time is 0, so the display of the result should be m3, m2, m1, m0.

CodePudding user response:

Turns out, the ListView extension I was using had a custom renderer for iOS which was causing the problem. Once I switched to Xamain's out-of-the-box ListView, the problem disappeared.

Morale of the story, be careful when using control extensions.

  •  Tags:  
  • Related