我正在嘗試爲我的WPF應用程序編寫自定義Main()
函數,以便我可以解析命令行並根據命令行配置GUI。我無法弄清楚如何獲取由Main()
的默認實現創建的MainWindow
實例。在App.g.cs
發現自動生成的實現如下:在WPF中獲取對自定義main()中的MainWindow的引用
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
#line 5 "..\..\..\App.xaml"
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
System.Uri resourceLocater = new System.Uri("/MyApplication;component/app.xaml", System.UriKind.Relative);
#line 1 "..\..\..\App.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.STAThreadAttribute()]
public static void Main() {
MyApplication.App app = new MyApplication.App();
app.InitializeComponent();
app.Run();
}
我遇到正在試圖獲得一個參考我的MainWindow
類被實例化後的問題(當然,這是實際上是通過StartupUri
完成)。我希望能夠做一些事情,如:
[System.STAThreadAttribute()]
public static void Main() {
MyApplication.App app = new MyApplication.App();
app.InitializeComponent();
MyApplication.MainWindow w = (MyApplication.MainWindow)app.MainWindow;
w.MyProgramIsAwesomeProperty = true;
app.Run();
}
但是,該app.MainWindow
總是null
。我也試過在Console.WriteLine
線以下,並設置斷點,但該計劃從未達到的回調:
[System.STAThreadAttribute()]
public static void Main() {
MyApplication.App app = new MyApplication.App();
app.LoadCompleted += app_LoadCompleted;
app.Activated += app_Activated;
app.InitializeComponent();
app.Run();
}
static void app_Activated(object sender, EventArgs e)
{
Console.WriteLine("Activated");
}
static void app_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
Console.WriteLine("LoadCompleted");
}
所以,我怎樣才能到MyApplication.MainWindow
參考之後,它已經在我的Main
函數實例化?
嘗試Application.Current.MainWindow – Tuco
也是'null'。 :-( –
我認爲這是因爲你需要創建一個MainWindow的實例,然後將它分配給Application.Current.MainWindow – Tuco