WPF ListBox Scroll to end automatically

后端 未结 9 784
耶瑟儿~
耶瑟儿~ 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:26

    Keep in mind that listBox.ScrollIntoView(listBox.Items[listBox.Items.Count - 1]); works only if you have no duplicate items. If you have items with the same contents it scrolls down to the first find.

    Here is the solution I found:

    ListBoxAutomationPeer svAutomation = (ListBoxAutomationPeer)ScrollViewerAutomationPeer.CreatePeerForElement(myListBox);
    
    IScrollProvider scrollInterface = (IScrollProvider)svAutomation.GetPattern(PatternInterface.Scroll);
    System.Windows.Automation.ScrollAmount scrollVertical = System.Windows.Automation.ScrollAmount.LargeIncrement;
    System.Windows.Automation.ScrollAmount scrollHorizontal = System.Windows.Automation.ScrollAmount.NoAmount;
    //If the vertical scroller is not available, the operation cannot be performed, which will raise an exception. 
    if ( scrollInterface.VerticallyScrollable )
        scrollInterface.Scroll(scrollHorizontal, scrollVertical);
    

提交回复
热议问题