WPF ProgressBar


When you have operations in your software that take a long time to complete, you might find that displaying a progress bar will make your users feel better. At least they know that something is happening and the program hasn’t crashed.

In this example I will just simulate a “long” process with the DispatcherTimer.

Below is the XAML code.

1<Window x:Class="ProgressBarSimple.MainWindow"
6        xmlns:local="clr-namespace:ProgressBarSimple"
7        mc:Ignorable="d"
8        WindowStartupLocation="CenterScreen"
9        Title="ProgressBarSimple" Height="150" Width="300">
10    <DockPanel>
11        <StatusBar DockPanel.Dock="Bottom">
12            <StatusBarItem>
13                <TextBlock Name="lblCursorPosition" />
14            </StatusBarItem>
15        </StatusBar>
16        <ProgressBar Name="pb" Height="25" DockPanel.Dock="Top"
17                     Minimum="0" Maximum="100" Value="2" />
18        <TextBox AcceptsReturn="True" Name="txtEditor" SelectionChanged="txtEditor_SelectionChanged" />
19    </DockPanel>
20</Window>

By default, the minimum is 0 and the maximum is 100.

1using System;
2using System.Windows;
3using System.Windows.Threading;
4 
5namespace ProgressBarSimple
6{
7    public partial class MainWindow : Window
8    {
9        public MainWindow()
10        {
11            InitializeComponent();
12            pb.Value = 3;
13            DispatcherTimer timer = new DispatcherTimer();
14            timer.Interval = TimeSpan.FromMilliseconds(20);
15            timer.Tick += timer_Tick;
16            timer.Start();
17        }
18        void timer_Tick(object sender, EventArgs e)
19        {
20            pb.Value = pb.Value + 1;
21        }
22        private void txtEditor_SelectionChanged(object sender, RoutedEventArgs e)
23        {
24            int row = txtEditor.GetLineIndexFromCharacterIndex(txtEditor.CaretIndex);
25            int col = txtEditor.CaretIndex - txtEditor.GetCharacterIndexFromLineIndex(row);
26            lblCursorPosition.Text = "Line " + (row + 1) + ", Char " + (col + 1);
27        }
28    }
29}