Application.Current.Windows不包含所有创建的Window

时间:2014-11-25 13:54:33

标签: c# wpf windows multithreading xaml

我按如下方式创建(并显示)了一个窗口:

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();

当我尝试使用以下命令遍历创建的Windows时使用:

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;
         }
     });
}

windowsList似乎只有两个Windows(MainWindowView,另一个)而不是NotificationPopUpView,这是什么原因?我不知道自己错过了什么?请向我解释有什么问题,如何更正?

1 个答案:

答案 0 :(得分:1)

  

这是什么原因?我不知道自己错过了什么?   请向我解释有什么问题,如何更正?

Application.Current.Windows仅包含主UI线程中存在的窗口。因为您在新主题上创建了notificationPopUp,所以它自然会在那里丢失。在除了主UI线程之外的任何其他线程上创建窗口并不是一个好习惯。如果涉及大量数据处理,则应将其与后台线程分开,而不是创建窗口以保持UI响应。

关于StackOverflow的类似问题:Get all windows from all threads