应用程序的主窗口打开一个正在进行的对话框,该对话框应调用后台线程。对话框应该出现,直到线程完成:
var dialog = new WorkInProgressDialog();
dialog = ShowDialg;
现在的问题是在哪里/如何调用WorkInProgressDialog
构造函数中的线程?如果在构造函数中调用它,那么在线程完成之前,对话框将不可见。
此外,该对话框应在线程完成后自动关闭。
以下是一个有望对您有所帮助的示例。WorkInProgressDialog:的一些简单标记
<Window x:Class="WorkInProgressExample.WorkInProgressDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WorkInProgressDialog" Height="100" Width="300" WindowStyle="None"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Border BorderThickness="3" CornerRadius="5" BorderBrush="Black" Padding="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="1" Name="WorkProgressTextBlock">Work in progress...</TextBlock>
<ProgressBar Grid.Row="2" Height="30" Name="WorkProgressBar"></ProgressBar>
</Grid>
</Border>
</Window>
然后在后面的代码中:
private bool _closeAuthorised = false;
public WorkInProgressDialog()
{
InitializeComponent();
WorkProgressBar.Maximum = 10;
WorkProgressBar.Minimum = 0;
Task.Factory.StartNew(() =>
{
// Do whatever processing you need to here
for (int i = 0; i < 10; i++)
{
// Any updates to the UI need to be done on the UI thread
this.Dispatcher.Invoke((Action)(() =>
{
WorkProgressBar.Value = i;
}));
Thread.Sleep(1000);
}
// Set the DialogResult and hence close, also on the UI thread
this.Dispatcher.Invoke((Action)(() =>
{
_closeAuthorised = true;
this.DialogResult = true;
}));
});
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
// If the user uses ALT+F4 to try andclose the loading dialog, this will cancel it
if (!_closeAuthorised)
e.Cancel = true;
base.OnClosing(e);
}
然后你想在哪里使用它:
var dialog = new WorkInProgressDialog();
bool? result = dialog.ShowDialog();