@@ -44,7 +44,7 @@ public static void SetIsEnabled(DependencyObject element, bool value)
4444
4545 private static void ItemsControl_Loaded ( object sender , RoutedEventArgs e )
4646 {
47- if ( sender is not ItemsControl itemsControl )
47+ if ( sender is not ItemsControl itemsControl || itemsControl . ItemsSource is not INotifyCollectionChanged notifyCollection )
4848 {
4949 return ;
5050 }
@@ -59,26 +59,31 @@ private static void ItemsControl_Loaded(object sender, RoutedEventArgs e)
5959 bool allowPause = GetAllowPause ( itemsControl ) ;
6060 bool autoScroll = true ;
6161
62- scrollViewer . ScrollChanged += ( s , ev ) => {
63- if ( scrollViewer . VerticalOffset == scrollViewer . ScrollableHeight )
64- {
65- autoScroll = true ;
66- }
67- else
62+ void ScrollChangedHandler ( object s , ScrollChangedEventArgs args )
63+ {
64+ autoScroll = scrollViewer . VerticalOffset == scrollViewer . ScrollableHeight || ! allowPause ;
65+ }
66+
67+ scrollViewer . ScrollChanged += ScrollChangedHandler ;
68+
69+ void CollectionChangedHandler ( object ? s , NotifyCollectionChangedEventArgs args )
70+ {
71+ if ( autoScroll && args . Action == NotifyCollectionChangedAction . Add )
6872 {
69- autoScroll = ! allowPause ;
73+ scrollViewer . ScrollToEnd ( ) ;
7074 }
71- } ;
75+ }
7276
73- if ( itemsControl . ItemsSource is INotifyCollectionChanged notifyCollection )
77+ notifyCollection . CollectionChanged += CollectionChangedHandler ;
78+
79+ void UnloadedHandler ( object s , RoutedEventArgs args )
7480 {
75- notifyCollection . CollectionChanged += ( s , ev ) => {
76- if ( autoScroll && ev . Action == NotifyCollectionChangedAction . Add )
77- {
78- scrollViewer . ScrollToEnd ( ) ;
79- }
80- } ;
81+ scrollViewer . ScrollChanged -= ScrollChangedHandler ;
82+ notifyCollection . CollectionChanged -= CollectionChangedHandler ;
83+ itemsControl . Unloaded -= UnloadedHandler ;
8184 }
85+
86+ itemsControl . Unloaded += UnloadedHandler ;
8287 }
8388
8489 private static void OnIsEnabledChanged ( DependencyObject d , DependencyPropertyChangedEventArgs e )
0 commit comments