I have a WPF ListBox that is set to scroll horizontally. The ItemsSource is bound to an ObservableCollection in my ViewModel class. Every time a new item is added, I want the ListBox to scroll to the right so that the new item is viewable.
The ListBox is defined in a DataTemplate, so I am unable to access the ListBox by name in my code behind file.
How can I get a ListBox to always scroll to show a latest added item?
I would like a way to know when the ListBox has a new item added to it, but I do not see an event that does this.
This is the solution I use that works, might help someone else;
So what i read in this topcs is a little bit complex for a simple action.
So I subscribed to scrollchanged event and then I used this code:
Bonus:
After it I made a checkbox where I could set when I want use the autoscroll function and I relaized I forgot some times uncheck the listbox if I saw some interesting information for me. So I decided I would like to create a intelligent autoscrolled listbox what react to my mouse action.
When I scolled to botton the checkbox checked true and stay my view on bottom if I scroulled up with mouse wheel the checkox will be unchecked and you can explorer you listbox.
MVVM-style Attached Behavior
This Attached Behavior automatically scrolls the listbox to the bottom when a new item is added.
In your
ViewModel
, you can bind to booleanIfFollowTail { get; set; }
to control whether auto scrolling is active or not.The Behavior does all the right things:
IfFollowTail=false
is set in the ViewModel, the ListBox no longer scrolls to the bottom on a new item.IfFollowTail=true
is set in the ViewModel, the ListBox instantly scrolls to the bottom, and continues to do so.Behavior C# Code
Bridge from events to Reactive Extensions
Finally, add this extension method so we can use all of the RX goodness:
Add Reactive Extensions
You will need to add
Reactive Extensions
to your project. I recommendNuGet
.I was not happy with proposed solutions.
Here is what I ended up with. Maybe it will save somebody some time.
I use this solution: http://michlg.wordpress.com/2010/01/16/listbox-automatically-scroll-currentitem-into-view/.
It works even if you bind listbox's ItemsSource to an ObservableCollection that is manipulated in a non-UI thread.