c# - 没有按钮的对话框内的WPF关闭对话框

问题描述 投票:0回答:2
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
c# wpf dialog
2个回答
0
投票

您应该在Init方法中使用Dispatcher。例如,像这样:

Application.Current.Dispatcher.Invoke(() => this.Close());

0
投票

await Loaded事件处理程序中运行和async任务:

public SecondWindow()
{
    InitializeComponent();
    Loaded += WindowLoaded;
}

private async void WindowLoaded(object sender, RoutedEventArgs e)
{
    await Task.Run(() => Init());
    Close();
}
© www.soinside.com 2019 - 2024. All rights reserved.