Search code examples
wpfitemscontrol

Show latest item added to an ItemsControl


I can't believe that I couldn't find a solution to this after searching google and SO for a half-hour.

I've got an ObservableCollection<string> in my ViewModel that a ListBox in my View is bound to:

<ListBox ItemsSource="{Binding Output}" IsSynchronizedWithCurrentItem="True" />

When a button is clicked, a new thread does some stuff and, using an Observable, the VM monitors strings coming back from that async operation and adds the strings to its Output ObservableCollection. The strings are getting added with no problem, but how to I get the view to always show the latest item (the one most recently added)?


Solution

  • Does your item show up in the list but just farther down? If that is the case all you need to do is tell the list to scroll that item into view. You can do this by subscribing to the ColllectionChanged of the ListBox.Items property. To do this is a little tricky because you have to cast it but you can do so with code like this:

    ((INotifyCollectionChanged)MainListBox.Items).CollectionChanged +=  ListBox_CollectionChanged;
    

    Then inside that event you can add code like this:

    private void ListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems.Count > 0)
            {
                Dispatcher.BeginInvoke(() =>
                {
                     MainListBox.ScrollIntoView(e.NewItems[0]);
                }, DispatcherPriority.SystemIdle);
            }
        }
    

    Also I just found a way you can do this with an attached property that is pretty cool. Check it out here: http://michlg.wordpress.com/2010/01/16/listbox-automatically-scroll-currentitem-into-view/