关于SingleInstance class on CodeProject,我有一个棘手的问题。
我希望能够在我的窗口加载之后处理命令行args,在我开始使用SingleInstance之前,我在MainWindow的Loaded事件中处理了所有这些。现在,我想我被迫把所有这些都放在我的App课程中,但我不知道如何从我的ViewModel访问任何属性或方法。
应用代码:
public partial class App : System.Windows.Application, ISingleInstanceApp
{
public static new App Current
{
get {
return System.Windows.Application.Current as App;
}
}
internal ApplicationInitializeDelegate ApplicationInitialize;
internal delegate void ApplicationInitializeDelegate(SplashScreen splashWindow);
private const string Unique = "Unique App Id";
public bool SignalExternalCommandLineArgs(IList<string> args)
{
//This executes for each instance after the first.
//We can activate the window and access properties/methods of type Window,
//but not of type MainWindow, and, therefore, have no
//access to ViewModel.
this.MainWindow.Activate();
return true;
}
[STAThread]
public static void Main(params string[] Arguments)
{
//Stops new windows from being created.
if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
{
App app = new App();
app.InitializeComponent();
app.Run();
SingleInstance<App>.Cleanup();
} else {
//Runs each time after first instance.
}
}
public App()
{
ApplicationInitialize = _applicationInitialize;
}
//I added this here while experimenting, though, obviously it doesn't do anything yet. Can we do something here, possibly?
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Length > 0)
{
}
}
private void _applicationInitialize(SplashScreen splashWindow)
{
//Do work and update splashWindow
//Create the main window on the UI thread.
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate ()
{
MainWindow = new MainWindow();
MainWindow.Show();
}));
}
}
修改1
我想出了一个非常肮脏(并不那么理想)的黑客,它给了我我想要的东西,但不是我认为我应该这样做的方式。
public bool SignalExternalCommandLineArgs(IList<string> args)
{
this.MainWindow.Activate();
this.MainWindow.Tag = args.Count > 0 ? args[1] : "";
return true;
}
这允许我直接将我正在尝试执行操作的文件的路径传递给我的MainWindow,以便在加载完所有内容后,我可以继续打开它。我讨厌这个事实,我已经使用了Tag属性,因为它感觉不对。任何替代方案?