Window.Show()不显示控件,但Window.ShowDialog()执行2

时间:2015-06-11 13:38:40

标签: c# wpf windows xaml

我这样做Window.Show() doesn't display controls but Window.ShowDialog() does来解决问题。但是,我有同样的问题状态。如何修改以下代码来解决此问题?

            TimeWindow aTimeWindow = new TimeWindow();
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += ((o, ea) => { 
                // Highly time consumable task
                _resetEvent.Set();
            });
            aTimeWindow.Show();
            bw.RunWorkerAsync();
            _resetEvent.WaitOne();
            aTimeWindow.Close();

_resetEvent是一个班级的领域。 TimeWindow只是一张TextBox WPF控件的图片。

1 个答案:

答案 0 :(得分:0)

您可以只是异步/等待,以便在工作完成时显示和关闭窗口。类似的东西:

private async void ShowWindow()
{
    var aTimeWindow = new TimeWindow();
    aTimeWindow.Show();
    await Task.Run((Action)DoWork);
    aTimeWindow.Close();    
}

private void DoWork()
{
    // perform long running work here
}

编辑:

不使用async / await

private void ShowWindow()
{
    var aTimeWindow = new TimeWindow();
    aTimeWindow.Show();

    Task.Run(()=>
    {
        DoWork();
    })
    .ContinueWith((t) =>
    {       
        Application.Current.Dispatcher.BeginInvoke((Action)(() => 
        {
            aTimeWindow.Close();    
        }));
    });
}

private void DoWork()
{
    // perform long running work here
}