How can I have a ListBox auto-scroll when a new item is added?

后端 未结 12 2362
走了就别回头了
走了就别回头了 2020-11-28 20:34

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 th

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 20:55

    The most straight-forward way i've found to do this, especially for listbox (or listview) that is bound to a data source is to hook it up with the collection change event. You can do this very easily at DataContextChanged event of the listbox:

        //in xaml 
        private void LogView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
          var src = LogView.Items.SourceCollection as INotifyCollectionChanged;
          src.CollectionChanged += (obj, args) => { LogView.Items.MoveCurrentToLast(); LogView.ScrollIntoView(LogView.Items.CurrentItem); };
        }
    

    This is actually just a combination of all the other answers i've found. I feel that this is such a trivial feature that we should not need to spend so much time (and lines of code) doing.

    If only there was an Autoscroll = true property. Sigh.

提交回复
热议问题