How to control the scroll position of a ListBox in a MVVM WPF app

后端 未结 4 580
后悔当初
后悔当初 2020-12-05 18:05

I have got a big ListBox with vertical scrolling enabled, my MVVM has New and Edit ICommands. I am adding new item to the end of the collection but I want the scrollbar also

4条回答
  •  情深已故
    2020-12-05 18:38

    I typically set IsSynchronizedWithCurrentItem="True" on the ListBox. Then I add a SelectionChanged handler and always bring the selected item into view, with code like this:

        private void BringSelectionIntoView(object sender, SelectionChangedEventArgs e)
        {
            Selector selector = sender as Selector;
            if (selector is ListBox)
            {
                (selector as ListBox).ScrollIntoView(selector.SelectedItem);
            }
        }
    

    From my VM I can get the default collection view and use one of the MoveCurrent*() methods to ensure that the item being edited is the current item.

    CollectionViewSource.GetDefaultView(_myCollection).MoveCurrentTo(thisItem);
    

    NOTE: Edited to use ListBox.ScrollIntoView() to accomodate virtualization

提交回复
热议问题