I have an ItemsControl
that is databound to a ObservableCollection
. I have this method in the code behind which adds a new model to the list. I would then like to scroll the new item (at the bottom of the list) into view.
I think the size of the ItemsControl
is not yet updated when I am querying the size, since the ActualHeight
before and after the addition of the model is the same. The effect of this code is to scroll to a point slightly above the new item.
How would I know what the new ActualHeight
is going to be?
Here is my code:
ViewModel.CreateNewChapter();
var height = DocumentElements.ActualHeight;
var width = DocumentElements.ActualWidth;
DocumentElements.BringIntoView(new Rect(0, height - 1, width, 1));
I think you need to call
BringIntoView
on the item container, not the ItemsControl itself :EDIT: actually this doesn't work, because at this point, the item container hasn't been generated yet... You could probably handle the
StatusChanged
event of theItemContainerGenerator
. I tried the following code :However it doesn't work either... for some reason,
ContainerFromItem
still returns null after the status changes toContainersGenerated
, and I have no idea why :SEDIT : OK, I understand now... this was because of the virtualization : the containers are generated only when they need to be displayed, so no containers are generated for hidden items. If you switch virtualization off for the ItemsControl (
VirtualizingStackPanel.IsVirtualizing="False"
), the solution above works fine.