Lately a colleague of mine had a requirement to add items to a ListView programmatically. After adding an item, the ListView was supposed to scroll automatically so that the newly item came into view. First attempts to use the ScrollIntoView method of the ListView failed. There was just no scrolling at all. So I decided to check things up and here are the results.
ListView uses an ItemContainerGenerator that generates the UI and the visual tree for the ListView and its items. Whenever you add an item to the ListView the generator recreates all the item container elements. It does this in an asynchronous way. Therefore if you add an item programmatically and call ScrollIntoView right afterwards the container items will not have been created at this time and that’s why you won’t see any changes in the UI.
The trick here is to subscribe to the StatusChanged event of the ItemContainerGenerator:
listView.ItemContainerGenerator.StatusChanged += new ItemContainerGenerator_StatusChanged;
In the event handler you can check if the current status of the generator is equal to GeneratorStatus.ContainersGenerated:
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
if(listView.ItemContainerGenerator.Status ==
GeneratorStatus.ContainersGenerated)
{
var info = listView.Items[listView.Items.Count - 1] as FileInfo;
if (info == null)
return;
listView.ScrollIntoView(info);
}
}