I'm porting an application from MAUI to WPF, it's a chat application so I made this CollectionView in MAUI that contains all the messages from all the users inside a single chat and like a real chat application, the layout of messages is from top to bottom, the most recent message is at the bottom and I wanted to reproduce this behavior using simply: ItemsUpdatingScrollMode="KeepLastItemInView".
I want the ListView to automatically scroll to the last message when:
- the view is opened (messages already present)
- a new message is added while the user is already at the bottom.
Expected behavior
When the window opens or when I press "Send", the last message should be visible (like a typical chat). If the user scrolls up manually, auto-scroll should be disabled until the user returns to bottom or sends a new message.
Actual behavior
The ListView opens at the top. When I add a message, it may end up hidden below the input area unless I manually scroll.
In the MAUI version I simply access the chat I want to write to, and it automatically scrolls down to show the last message, or if the user write a message on the box and press Send, the view scrolls down automatically and focuses on the last message sent.
The thing is that now I have to reproduce the same thing in WPF, but obviously in WPF there isn't a CollectionView tag or even an ItemsUpdatingScrollMode property for a ListView.
Here's what I have in my XAML:
<ListView x:Name="MessagesList"
Background="Transparent" Margin="8,0,0,0" BorderThickness="0"
Grid.Row="1" ItemTemplate="{StaticResource ChatItemTemplate}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ItemsSource="{Binding Messages}"/>
Question
What is the correct WPF approach to keep a ListView automatically scrolled to the last item (like a chat), similar to ItemsUpdatingScrollMode="KeepLastItemInView" in MAUI?
I've already tried handling CollectionChanged and calling ScrollIntoView() from code-behind and from an attached behavior, but none of them worked reliably. I'm looking for the idiomatic WPF way to achieve this chat-like auto-scroll behavior.
ListViewso your view model can control which item to scroll to.ListView's selected items property to yourViewModel. TheScrollToSelectedListBoxItemBehavioronly scrolls to the selected either when theSelectionChangedor theIsVisibleChangedevent from theListViewis triggered. You'd now need to trigger theSelectionChangedevent by changing the selected item (i.e. via 2 way binding on your view model)ScaleY=-1to the LayoutTransform of the ScrollViewer and the item container, e.g. the ContentPresenter of an ItemsControl.