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.
If the above code doesn't work for you, give this a try
Usage in XAML
Using this in MVVM can be easily accomplished via an attached behavior like so:
Then in the View ad this reference at the top:
And do this:
Now when the SelectedItem changes the behavior will do the BringIntoView() call for you.
I typically set
IsSynchronizedWithCurrentItem="True"
on theListBox
. Then I add aSelectionChanged
handler and always bring the selected item into view, with code like this: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.NOTE: Edited to use
ListBox.ScrollIntoView()
to accomodate virtualizationThis is the attached property form of the accepted answer:
Usage: