Application.Current.Shutdown() is not killing my application

后端 未结 7 819
执念已碎
执念已碎 2021-02-05 03:39

I\'ve just started a new C#/WPF application and am using the NotifyIcon from the WPF Contrib project. I can start the program, add an \"Exit\" MenuItem to the NotifyIcon\'s Cont

相关标签:
7条回答
  • 2021-02-05 04:35

    Make absolutely sure you aren't creating any Window objects that you never Show()

    For some insane reason WPF adds windows to Application.Windows on CREATION and not when you first call Show(). If you have Application.Current.Shutdown set to ShutdownMode.OnLastWindowClose then these windows (that you never even displayed) will prevent the app from shutting down.

    Lets say you open a child window of your main window like this

    Console.WriteLine("Window count : " + Application.Windows.Count);
    var window = new OrderDetailsWindow();
    Console.WriteLine("Window count : " + Application.Windows.Count);
    window.Show();
    

    Before you even call Show() you'll see that Applications.Windows now shows 2. The app will only shutdown when Windows.Count is zero.


    My situation:

    I have a WindowFactory that takes a viewmodel and creates a window for the model passed in.

    Somehow over the years my copy and pasting had yielded this :

     if (viewModel is DogModel)
     {
         window = new DogWindow();
     }
     else if (viewModel is CatViewModel) 
     {
          window = new CatWindow();
     }
     if (viewModel is DogModel)          
     {
         window = new DogWindow();    
     }
    
     window.DataContext = viewModel;
     window.Show();
    

    So when viewModel was DogModel I ended up creating TWO DogWindow objects so Application.Windows.Count was 3 when I expected it to be 2. Since Application.Shutdown was waiting for all windows to be closed it never got activated - even though I never even opened the window!

    I would always have assumed that Show() was needed to activate the window, but that was a wrong assumption - so my app never exited.

    0 讨论(0)
提交回复
热议问题