2011-08-30 150 views
1

我需要當前窗口來顯示一個自定義的MessageBox。我這樣做:創建另一個線程來獲取當前窗口(System.Windows.Application.Current.MainWindow)

Window owner = System.Windows.Application.Current.MainWindow; 

有時它的工作原理。當它不工作,我得到這個錯誤:

System.InvalidOperationException: {"The calling thread cannot access this object because a different thread owns it."} 
InnerException: null 
Message: The calling thread cannot access this object because a different thread owns it. 

會解決是踢這個調用關閉以比主線程一個單獨的線程?如果是這樣,我該怎麼做?謝謝。

回答

9

你需要使用的調度和調用/的BeginInvoke封送回調到UI線程:

System.Windows.Application.Current.Dispatcher.Invoke((Action)() => 
{ 
     Window owner = System.Windows.Application.Current.MainWindow; 

     // Use owner here - it must be used on the UI thread as well.. 
     ShowMyWindow(owner); 
}); 
+0

+1 - 基本上,我在寫這是你的貼吧。 – Tejs

相關問題