SecondWindow secdWin = new SecondWindow();
secdWin.ShowDialog();
上面的代码来自我的MainWindow.xaml.cs
新窗口产生并执行它想要做的事情,然后我尝试从内部关闭它。
这是来自我的SecondWindow.xaml.cs
public partial class SecondWindow : Window
{
public SecondWindow()
{
InitializeComponent();
Task initTask = new Task(() => Init());
initTask.Start();
}
private void Init()
{
server = new ServerReply();
//.. doing stuff with the server.
server.Reply = response.Content;
//I want to close the SecondWindow here.
}
}
我试过了:
var w = Application.Current.Windows[0];
w.Close();
它不起作用,我也尝试过:
this.Close();
但无论我做什么,我得到的只是:
Exception thrown: 'System.InvalidOperationException' in WindowsBase.dll
您应该在Init方法中使用Dispatcher。例如,像这样:
Application.Current.Dispatcher.Invoke(() => this.Close());
在await
Loaded事件处理程序中运行和async
任务:
public SecondWindow()
{
InitializeComponent();
Loaded += WindowLoaded;
}
private async void WindowLoaded(object sender, RoutedEventArgs e)
{
await Task.Run(() => Init());
Close();
}