我的视图中有一个按钮。单击此按钮时,从我视图模型中的某个点开始,我创建了一个线程。从这个线程我通过调用'NewWindowHandler'方法在主窗口的顶部创建并打开一个模态辅助窗口:
查看模型:
private void NewWindowHandler(object sender, RoutedEventArgs e)
{
Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();
}
private void ThreadStartingPoint()
{
ShowSecondaryWindow();
System.Windows.Threading.Dispatcher.Run();
}
private System.Windows.Window secondaryWindow = null;
private void ShowSecondaryWindow()
{
if (secondaryWindow == null)
{
secondaryWindow = new SecondaryWindow();
}
if (secondaryWindow.IsVisible == false)
secondaryWindow.ShowDialog();
}
SecondaryWindows是一个XAML视图,一个典型的窗口如下:
<Window x:Class="MyApps.WPF.SecondaryWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Items -->
</Window>
secondaryWindow是我的视图模型中的全局变量。
稍后,在我的视图模型的另一点,我希望在完成长时间操作时关闭这个打开的辅助窗口:
private void CloseSecondaryWindow()
{
if (secondaryWindow != null)
{
if (secondaryWindow.Dispatcher.CheckAccess())
{
secondaryWindow.Close();
secondaryWindow = null;
}
else
{
secondaryWindow.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(secondaryWindow.Close));
}
}
}
这似乎有效,二级窗口关闭。问题是,当我再次单击WPF按钮并再次显示辅助窗口时,它会崩溃 在ShowSecondaryWindow方法中的secondaryWindow.ShowDialog(),说:
The subprocess that makes the call cannot get access to this object because the owner is another subprocess.
此外,我不确定是否是因为我没有以正确的方式关闭先前的辅助窗口。
有什么想法吗?
我正在使用Visual Studio 2008和.NET Framework 3.5 SP1。