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
答案 0 :(得分:0)
您应该在Init方法中使用Dispatcher。例如,像这样:
Application.Current.Dispatcher.Invoke(() => this.Close());
答案 1 :(得分:0)
在await
加载的事件处理程序中运行并async
运行任务:
public SecondWindow()
{
InitializeComponent();
Loaded += WindowLoaded;
}
private async void WindowLoaded(object sender, RoutedEventArgs e)
{
await Task.Run(() => Init());
Close();
}