Application.Current控制台应用程序中的"null"

em7*_*m70 10 .net c# wpf f# multithreading

我目前正在尝试使用WPF组件,该组件使用来自WPF应用程序的Application.Current,但由于几个原因我从不调用Application.Run(也不是一个选项).结果是NullReferenceException.

我基本上试图从控制台应用程序中显示同一个WPF窗口的多个实例.任何建议(以及C#/ F#中的代码示例)都会受到欢迎!

提前致谢

Rob*_*sen 15

只是提供替代解决方案.可以在不打开任何窗口的情况下保持应用程序运行.对我来说,这感觉不那么'黑客'.:) http://msdn.microsoft.com/en-us/library/system.windows.application.shutdownmode.aspx

public class AppCode : Application
{
   // Entry point method
   [STAThread]
   public static void Main()
   {
      AppCode app = new AppCode();
      app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
      app.Run();
      ...
      app.Shutdown();
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑:好的,这有点麻烦.Application.Run将阻塞,因此它需要在自己的线程中运行.当它在自己的线程中运行时,主线程和ui线程之间的任何交互最好由Application.Current.Dispatcher.Invoke完成.这是一些工作代码,假设您有一个继承自Application的类.我正在使用WPF项目模板为您创建的修改后的App.xaml/App.xaml.cs,以免费处理ResourceDictionaries.

public class Program
{
  // Entry point method
  [STAThread]
  public static void Main()
  {
     var thread = new System.Threading.Thread(CreateApp);
     thread.SetApartmentState(System.Threading.ApartmentState.STA);
     thread.Start();

     // This is kinda shoddy, but the thread needs some time 
     // before we can invoke anything on the dispatcher
     System.Threading.Thread.Sleep(100);

     // In order to get input from the user, display a
     // dialog and return the result on the dispatcher
     var result = (int)Application.Current.Dispatcher.Invoke(new Func<int>(() =>
        {
           var win = new MainWindow();
           win.ShowDialog();
           return 10;
        }), null);

     // Show something to the user without waiting for a result
     Application.Current.Dispatcher.Invoke(new Action(() =>
     {
        var win = new MainWindow();
        win.ShowDialog();
     }), null);

     System.Console.WriteLine("result" + result);
     System.Console.ReadLine();

     // This doesn't really seem necessary 
     Application.Current.Dispatcher.InvokeShutdown();
  }

  private static void CreateApp()
  {
     App app = new App();
     app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
     app.Run();
  }
}
Run Code Online (Sandbox Code Playgroud)


lox*_*xxy 6

以下是Application类的预期行为:

  • 第一个打开的窗口是MainWindow.
  • 列表中唯一的窗口变为MainWindow(如果要删除其他窗口).
  • 如果Windows列表中没有窗口,则应用程序类旨在退出.

检查此链接.

所以基本上你不能运行一个应用程序,没有任何窗口打开.保持窗户打开但隐藏.


如果我误解了您的问题,那么以下类似的案例可能会有所帮助: