@@ -403,17 +403,38 @@ public void RemoveSingleItem(int id)
403403 _refresh = true ;
404404 }
405405
406-
407406 /// <summary>
408407 /// Called when [items source changed].
409408 /// </summary>
410409 private async Task OnItemsSourceChanged ( )
411410 {
412- ThumbWidth = _originalWidth ;
413- ThumbHeight = _originalHeight ;
411+ // Cancel any ongoing loads
412+ _cancellationTokenSource ? . Cancel ( ) ;
413+ _cancellationTokenSource ? . Dispose ( ) ;
414+
415+ // Unsubscribe events and clear dictionaries
416+ foreach ( var img in ImageDct ? . Values ?? Enumerable . Empty < Image > ( ) )
417+ {
418+ img . MouseDown -= ImageClick_MouseDown ;
419+ img . MouseRightButtonDown -= ImageClick_MouseRightButtonDown ;
420+ img . Source = null ;
421+ }
422+
423+ foreach ( var cb in ChkBox ? . Values ?? Enumerable . Empty < CheckBox > ( ) )
424+ {
425+ cb . Checked -= CheckBox_Checked ;
426+ cb . Unchecked -= CheckBox_Unchecked ;
427+ }
414428
415- // Clear existing images from the grid
416429 Thb . Children . Clear ( ) ;
430+ Keys ? . Clear ( ) ;
431+ ImageDct ? . Clear ( ) ;
432+ ChkBox ? . Clear ( ) ;
433+ Border ? . Clear ( ) ;
434+ Selection ? . Clear ( ) ;
435+
436+ ThumbWidth = _originalWidth ;
437+ ThumbHeight = _originalHeight ;
417438
418439 await LoadImages ( ) ;
419440
@@ -811,7 +832,7 @@ private void DeselectAll_Click(object sender, RoutedEventArgs e)
811832 // Take a snapshot to avoid modifying while enumerating
812833 var selectedIds = Selection . Keys . ToList ( ) ;
813834
814- Application . Current . Dispatcher . Invoke ( ( ) =>
835+ Application . Current . Dispatcher . BeginInvoke ( ( ) =>
815836 {
816837 foreach ( var id in selectedIds )
817838 {
0 commit comments