简体   繁体   中英

Application.Current.Windows doesn't contain all created Window

I created (and shown) a Window as follows :

var thread = new Thread(() =>
   {
        notificationPopUp = new NotificationPopUpView(unreadNotifications.First().session_s, unreadNotifications.First().secondry_msg);
        notificationPopUp.Show();
        Dispatcher.Run();

   });

thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();

when I try to itterate through the created Windows using :

Application.Current.Dispatcher.Invoke(() =>
{
     windowsList = Application.Current.Windows.Cast<Window>();
});

foreach (var window in windowsList)
{
     Application.Current.Dispatcher.Invoke(() =>
     {
         if (window.DataContext == viewModel)
         {
              returnValue = window;
         }
     });
}

The windowsList seem to have only two Windows (the MainWindowView, and another one) but not the NotificationPopUpView , what would be the cause of this ? I don't know what I'm missing ? please explain to me what is the problem and how can I correct this ?

what would be the cause of this ? I don't know what I'm missing ? please explain to me what is the problem and how can I correct this ?

Application.Current.Windows only contains windows that exist on the main UI thread. Because you created notificationPopUp on a new thread, it's naturally missing there. It's not good practice to create windows on any other thread but the main UI thread. If there is a lot of data processing involved, you should separate that to a background thread instead of the window creation to keep the UI responsive.

Similiar question on StackOverflow: Get all windows from all threads .

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