Lordalcol
Lordalcol

Reputation: 1020

ListView does not update immediately after I add a new item to the ObservableCollection

I am learning Xamarin.Forms and I have created a new project with Visual Studio 2019, using the Master-Detail project template. I am using UWP (as I want to make a Windows 10 app).

Why does the list view not show up immediately after I add the new item? Is this caused by slowness in the event/message passing, or is there an animation that is slowing it down on purpose?

In this sample, everything is happening in a local ObservableCollection, and there are only a few items in it, so I expect it to be able to display the change immediately.

Example:

Shows adding an item to an ObservableCollection bound to a ListView

The code is generated by Visual Studio, I can provide it, but I haven't really made any change.

EDIT: Since I suspect this is related to the events generated by the ObservableCollection and the bindings in the ListView, I tried the following change, which worked:

MessagingCenter.Subscribe<NewItemPage, Item>(this, "AddItem", async (obj, item) =>
{
    var newItem = item as Item;
    Items.Add(newItem);
    await DataStore.AddItemAsync(newItem);
});

To:

MessagingCenter.Subscribe<NewItemPage, Item>(this, "AddItem", async (obj, item) =>
{
    var newItem = item as Item;
    var tmp = new ObservableCollection<Item>();
    foreach (var i in Items)
    {
        tmp.Add(i);
    }
    tmp.Add(newItem);
    Items = tmp;
    OnPropertyChanged(nameof(Items));
    await DataStore.AddItemAsync(newItem);
});

Of course, this is inefficient and not ideal but might help someone else figure out what is going on in the original version. Behaviour after the change:

ListView loading immediately after the change

Upvotes: 1

Views: 521

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39082

In UWP the views for the navigation back stack are not kept in memory to conserve it, so when you navigate to another page and back, the previous page is reconstructed. In this case however, the reason why it "fades" in is animation, that is built into the default NavigationPageRenderer in UWP.

The animation is occurring here in the code, it should be possible to disable the animation by setting the isAnimated flag to false on the right place, but I don't have my dev device with me right now so I can't test it.

Update

It seems that this is really a problem with the UWP implementation of either ListView or MasterDetailPage.

Workaround

Adding a small delay to the message handler subscription fixes the issue:

MessagingCenter.Subscribe<NewItemPage, Item>(this, "AddItem", async (obj, item) =>
{
    await Task.Delay(100);
    var newItem = item as Item;
    Items.Add(newItem);
    await DataStore.AddItemAsync(newItem);
});

I have reported the problem on GitHub as an issue.

Upvotes: 2

Related Questions