Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

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

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 to auto position to the End when I call my MVVM-AddCommand. I am also making an item editable(By calling EditCommand with a particular row item) from some other part of the application so that my ListBoxItem getting in to edit mode using DataTrigger, but how will I bring that particular row(ListBoxItem) to the view by adjusting the scroll position.

If I am doing it in the View side I can call listBox.ScrollInToView(lstBoxItem). But what is the best way to solve this common Scroll issue from an MVVM perspective.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...