2014-02-14 155 views
3

我開發了一個示例WPF項目。
這裏是主窗口的代碼隱藏:關閉子窗口後將WPF主窗口放在後臺

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Navigation; 
using System.Windows.Shapes; 
using Telerik.Windows.Controls; 

namespace MainWindowInBackground 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      Window l_hostWindow = new Window() 
      { 
       Owner = System.Windows.Application.Current.MainWindow, 
       WindowStartupLocation = WindowStartupLocation.CenterOwner, 
       Content = "Test" 
      }; 

      l_hostWindow.Show(); 

      Window l_hostWindow2 = new Window() 
      { 
       Owner = System.Windows.Application.Current.MainWindow, 
       WindowStartupLocation = WindowStartupLocation.CenterOwner, 
       Content = "Test 2" 
      }; 

      l_hostWindow2.Show(); 
      l_hostWindow2.Close(); 

      //MessageBox.Show(this, "MessageBox", "MessageBox", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK); 
     } 
    } 
} 

當用戶點擊按鈕:

  1. R1被創建和顯示
  2. R2創建窗口,並顯示
  3. 一個窗口
  4. R2窗口關閉

我已經完成了以下操作:

  • 我已經啓動了應用程序。行動之後採取截圖:

enter image description here

  • 我已經點擊了按鈕。顯示R1窗口。行動之後採取截圖:

enter image description here

  • 我已經關閉了R1的窗口。主窗口已自動置於後臺。截圖行動之後採取:

enter image description here

能有人請解釋我爲什麼在主窗口已經被自動放入背景,以及如何避免呢? 預先感謝您的幫助

+0

嘗試設置'childWindow.Owner = Application.Current.MainWindow;'。 – Sheridan

回答

4

不能告訴你爲什麼它發送到後臺,但保持它在前臺的方式,重點是讓孩子窗口的所有者和調用的Window.Focus()方法父窗口當子窗口關閉時...

public ChildWindow() 
{ 
    InitializeComponent(); 
    Owner = Application.Current.MainWindow; 
} 

private void ChildWindow_OnClosed(object sender, WindowClosedEventArgs e) 
{ 
    if (Owner == null) return; 
    Owner.Focus(); 
}