Async Progress Bar
<Window x:Class="HDI_WPF_AsyncProgressBar_cs.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="400" Width="400">
<Grid>
<StackPanel>
<Button x:Name="btnBegin" HorizontalAlignment="Center" Content="Start Long Process" Click="btnBegin_Click" />
<Button x:Name="btnInteract" HorizontalAlignment="Center" Content="Interact with UI" Click="btnInteract_Click" />
</StackPanel>
<Border x:Name="bdrProgress" Visibility="Hidden" Background="BurlyWood" CornerRadius="10" BorderBrush="DarkGray" BorderThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel>
<Grid Margin="5">
<ProgressBar x:Name="prgProgress" Width="200" Height="20" Minimum="0" Maximum="1" />
<TextBlock x:Name="txtProgress" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
<Button x:Name="btnCancel" Content="Cancel" HorizontalAlignment="Right" Margin="3" Click="btnCancel_Click" />
</StackPanel>
</Border>
</Grid>
</Window>
public partial class Window1 : Window
{
int counter = 0;
bool iscanceled = false;
public Window1()
{
InitializeComponent();
}
private void btnBegin_Click(object sender, RoutedEventArgs e)
{
bdrProgress.Visibility = Visibility.Visible;
new Thread(
delegate()
{
DoLongRunningProcess();
}
).Start();
}
private void btnInteract_Click(object sender, RoutedEventArgs e)
{
this.Title = counter++.ToString();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.iscanceled = true;
}
private void DoLongRunningProcess()
{
Thread.Sleep(2000);
if (!iscanceled)
{
Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress.SetValue(ProgressBar.ValueProperty, .5); }, null);
Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress.SetValue(TextBlock.TextProperty, "50%"); }, null);
Thread.Sleep(2000);
if (!iscanceled)
{
Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgProgress.SetValue(ProgressBar.ValueProperty, 1.0); }, null);
Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { txtProgress.SetValue(TextBlock.TextProperty, "100%"); }, null);
}
}
Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { bdrProgress.SetValue(Border.VisibilityProperty, Visibility.Collapsed); }, null);
}
}

浙公网安备 33010602011771号