WPF ListBox Scroll to end automatically

后端 未结 9 805
耶瑟儿~
耶瑟儿~ 2020-12-13 08:25

In my application, I have a ListBox with items. The application is written in WPF.

How can I scroll automatically to the last added item? I want the

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 09:11

    The most easiest way to achieve autoscrolling is to hook on the CollectionChanged event. Just add that functionality to a custom class which derives from ListBox control:

    using System.Collections.Specialized;
    using System.Windows.Controls;
    using System.Windows.Media;
    
    namespace YourProgram.CustomControls
    {
      public class AutoScrollListBox : ListBox
      {
          public AutoScrollListBox()
          {
              if (Items != null)
              {
                  // Hook to the CollectionChanged event of your ObservableCollection
                  ((INotifyCollectionChanged)Items).CollectionChanged += CollectionChange;
              }
          }
    
          // Is called whenever the item collection changes
          private void CollectionChange(object sender, NotifyCollectionChangedEventArgs e)
          {
              if (Items.Count > 0)
              {
                  // Get the ScrollViewer object from the ListBox control
                  Border border = (Border)VisualTreeHelper.GetChild(this, 0);
                  ScrollViewer SV = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
    
                  // Scroll to bottom
                  SV.ScrollToBottom();
              }
          }
      }
    }
    

    Add the namespace of the custom control to your WPF window and use the custom ListBox control:

    
    
        
    
    
    

提交回复
热议问题