2011-04-18 131 views
23

我想不起來的愚蠢簡單的問題。如何切換WPF窗口?

我有一個WPF應用程序,我想先顯示一個登錄對話框(在主窗口出現之前)。

如果用戶登錄成功,那麼我想顯示主窗口,如果沒有,我想退出應用程序。

如何正確地做到這一點?

回答

41

我想我想通了我想做什麼。

1)我需要將App.xaml中的「StartupUri」設置爲「Logon.xaml」,其中Logon.xaml是我的登錄窗口。

2)LogonButton_Click事件處理程序,添加以下

if (blnAuthenticateSuccessful) { 
    MainWindow main = new MainWindow(); 
    App.Current.MainWindow = main; 
    this.Close(); 
    main.Show(); 
} 

這似乎完成我想要的東西。

3

如果您想要顯示一個新窗口以允許用戶輸入他們的登錄信息,那麼我在下面添加了一些代碼。然而,創建一個真正的模態對話框在WPF中稍微複雜一點,所以我在這裏沒有解釋它。有一個關於在WPF模態對話框此信息:http://msdn.microsoft.com/en-us/library/aa969773.aspx

從可以打開的登錄窗口,並隱藏與此主窗口中的主窗口:

// Code for MainWindow 

// Create a new instance of the login window and then show it 
LoginWindow loginWindow = new LoginWindow(); 
loginWindow.Show(); 

// Hide the MainWindow until later 
this.Hide(); 

然後用這個登錄頁面上展示主窗口再次一旦用戶已經登錄:

// Code for Login window 

// This code finds the main window again and shows it 
Application.Current.MainWindow.Show(); 
+0

什麼事件你會把這個,讓用戶沒有看到主窗口第一? – Sako73 2011-04-19 00:58:44

+0

@ Sako73如果你把我給你的第一部分代碼放到MainWindow構造函數中,它將很好地工作。然後,當加載MainWindow時,它將立即打開登錄窗口,並隱藏MainWindow。 – 2011-04-19 01:08:21