简体   繁体   中英

WPF ListView Control Scroll to Bottom on PropertyChanged

I have a class called Logger, which has an ObservableCollection which holds all of the item data that is bound to a ListView control on my MainWindow class.

Inside the Logger class I raise the PropertyChangedEventHandler event to tell the UI that the collection has been updated. At this point I would also like to update the UI to scroll the ListView to the bottom.

Where or how would I go about this? I was looking for an attribute of the XAML control like "OnPropertyChanged" and inside it I could do something to scroll to the bottom.

I know that from within a class that has an instance of the MainWindow I can simply use the ScrollIntoView method on the LV box, but since I don't have an instance of the Window in the Logger class, how can I achieve this?

Sorry if this is straightforward, I'm in the early stages of WPF!

Cheers, Dave

  1. Assuming that your program is always using the same ObservableCollection object, I don't think you need to raise the PropertyChangedEventHandler as you collection is observable, which means whenever you add/remove items from the collection the UI side will be updated accordingly. PropertyChangedEventHandler is needed only if you will assign the Property with a new ObservableCollection object.

  2. To scroll to the last item, I would listen to the CollectionChanged event of the ObservableCollection and then call the listview's scrollintoview method with the last item in the ObservableCollection if the NotifyCollectionChangedAction is NotifyCollectionChangedAction.Add. NOTE: a. You may need to call UpdateLayout before ScrollIntoView. b. Need to execute the UpdateLayout/ScrollIntoView after the CollectionChanged event. Can use the UI's Dispatcher.BeginInvoke to call methods later after the event.

One way could be first set IsSynchronizedWithCurrentItem="True" for your list then set the selected item of your observationcollection with CollectionViewSource.GetDefaultView(_yourCollection).MoveCurrentTo(selectedItem); in your ViewModel and finally handling SelectionChanged event of your listbox in your View and call ScrollIntoView of your listbox. The other more straight way is using Behaviors. Both solutions are explained here.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM