@@ -55,7 +55,7 @@ public class DialogHost : ContentControl
55
55
/// </summary>
56
56
public static readonly RoutedCommand CloseDialogCommand = new ( ) ;
57
57
58
- private static readonly HashSet < DialogHost > LoadedInstances = new ( ) ;
58
+ private static readonly HashSet < WeakReference < DialogHost > > LoadedInstances = new ( ) ;
59
59
60
60
private DialogOpenedEventHandler ? _asyncShowOpenedEventHandler ;
61
61
private DialogClosingEventHandler ? _asyncShowClosingEventHandler ;
@@ -200,9 +200,24 @@ private static DialogHost GetInstance(object? dialogIdentifier)
200
200
{
201
201
if ( LoadedInstances . Count == 0 )
202
202
throw new InvalidOperationException ( "No loaded DialogHost instances." ) ;
203
- LoadedInstances . First ( ) . Dispatcher . VerifyAccess ( ) ;
204
203
205
- var targets = LoadedInstances . Where ( dh => dialogIdentifier == null || Equals ( dh . Identifier , dialogIdentifier ) ) . ToList ( ) ;
204
+ List < DialogHost > targets = new ( ) ;
205
+ foreach ( var instance in LoadedInstances . ToList ( ) )
206
+ {
207
+ if ( instance . TryGetTarget ( out DialogHost ? dialogInstance ) )
208
+ {
209
+ dialogInstance . Dispatcher . VerifyAccess ( ) ;
210
+ if ( dialogIdentifier is null || Equals ( dialogIdentifier , dialogInstance . Identifier ) )
211
+ {
212
+ targets . Add ( dialogInstance ) ;
213
+ }
214
+ }
215
+ else
216
+ {
217
+ LoadedInstances . Remove ( instance ) ;
218
+ }
219
+ }
220
+
206
221
if ( targets . Count == 0 )
207
222
throw new InvalidOperationException ( $ "No loaded DialogHost have an { nameof ( Identifier ) } property matching { nameof ( dialogIdentifier ) } ('{ dialogIdentifier } ') argument.") ;
208
223
if ( targets . Count > 1 )
@@ -671,9 +686,10 @@ internal void InternalClose(object? parameter)
671
686
672
687
protected override void OnPreviewMouseDown ( MouseButtonEventArgs e )
673
688
{
674
- var window = Window . GetWindow ( this ) ;
675
- if ( window != null && ! window . IsActive )
689
+ if ( Window . GetWindow ( this ) is { } window && ! window . IsActive )
690
+ {
676
691
window . Activate ( ) ;
692
+ }
677
693
base . OnPreviewMouseDown ( e ) ;
678
694
}
679
695
@@ -733,10 +749,19 @@ private string GetStateName()
733
749
=> IsOpen ? OpenStateName : ClosedStateName ;
734
750
735
751
private void OnUnloaded ( object sender , RoutedEventArgs routedEventArgs )
736
- => LoadedInstances . Remove ( this ) ;
752
+ {
753
+ foreach ( var weakRef in LoadedInstances . ToList ( ) )
754
+ {
755
+ if ( ! weakRef . TryGetTarget ( out DialogHost ? dialogHost ) ||
756
+ Equals ( dialogHost , this ) )
757
+ {
758
+ LoadedInstances . Remove ( weakRef ) ;
759
+ }
760
+ }
761
+ }
737
762
738
763
private void OnLoaded ( object sender , RoutedEventArgs routedEventArgs )
739
- => LoadedInstances . Add ( this ) ;
764
+ => LoadedInstances . Add ( new WeakReference < DialogHost > ( this ) ) ;
740
765
741
766
}
742
767
}
0 commit comments