C# winforms程序中的XAML窗口
当我在Winforms窗体上使用一个按钮打开一个用XAML创建的窗口时,它第一次正常工作,然后我关闭该窗口并重新单击该按钮,但是在正在创建的窗口的C# winforms程序中的XAML窗口,c#,winforms,xaml,C#,Winforms,Xaml,当我在Winforms窗体上使用一个按钮打开一个用XAML创建的窗口时,它第一次正常工作,然后我关闭该窗口并重新单击该按钮,但是在正在创建的窗口的InitializeComponent()上,我得到一个异常消息,“应用程序对象正在关闭” 我曾尝试将其作为用户控件托管在元素主机中,但问题仍然相同。在普通应用程序中,WinForms和WPF环境都由应用程序类型启动,该类型通常从主方法调用 在这里,WPF环境不会发生这种情况,这会导致问题。如果要从WinForms应用程序显示WPF窗口,则需要启动di
InitializeComponent()
上,我得到一个异常消息,“应用程序对象正在关闭”
我曾尝试将其作为用户控件托管在
元素主机中,但问题仍然相同。在普通应用程序中,WinForms和WPF环境都由应用程序
类型启动,该类型通常从主
方法调用
在这里,WPF环境不会发生这种情况,这会导致问题。如果要从WinForms应用程序显示WPF窗口,则需要启动dispatcher。最好在新线程中执行此操作,以便可以根据需要关闭任意次数:
private void ShowWpfWindow()
{
// This delegate is executed in new thread
ThreadStart showWindow = () =>
{
var window = new RestoreSettingsWindow(); // your window to show
// making sure that the thread can exit when the window is closed
window.Closed += (sender, e) => Dispatcher.InvokeShutdown();
window.Show();
// Starts the dispatcher in the new thread and does not let the thread exit.
// This call is returned when the window is closed (due to the Closed event handler)
System.Windows.Threading.Dispatcher.Run();
};
// Creating and starting an STA thread for the WPF window
Thread wpfThread = new Thread(showWindow);
wpfThread.SetApartmentState(ApartmentState.STA);
wpfThread.Priority = ThreadPriority.Normal;
wpfThread.Start();
}
private void ShowWpfWindow()
{
// This delegate is executed in new thread
ThreadStart showWindow = () =>
{
var window = new RestoreSettingsWindow(); // your window to show
// making sure that the thread can exit when the window is closed
window.Closed += (sender, e) => Dispatcher.InvokeShutdown();
window.Show();
// Starts the dispatcher in the new thread and does not let the thread exit.
// This call is returned when the window is closed (due to the Closed event handler)
System.Windows.Threading.Dispatcher.Run();
};
// Creating and starting an STA thread for the WPF window
Thread wpfThread = new Thread(showWindow);
wpfThread.SetApartmentState(ApartmentState.STA);
wpfThread.Priority = ThreadPriority.Normal;
wpfThread.Start();
}