2011-08-30 42 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

相关问题