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.

<Window x:Class="ProgressBarSimple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ProgressBarSimple"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="ProgressBarSimple" Height="150" Width="300">
    <DockPanel>
        <StatusBar DockPanel.Dock="Bottom">
            <StatusBarItem>
                <TextBlock Name="lblCursorPosition" />
            </StatusBarItem>
        </StatusBar>
        <ProgressBar Name="pb" Height="25" DockPanel.Dock="Top"
                     Minimum="0" Maximum="100" Value="2" />
        <TextBox AcceptsReturn="True" Name="txtEditor" SelectionChanged="txtEditor_SelectionChanged" />
    </DockPanel>
</Window>

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

using System;
using System.Windows;
using System.Windows.Threading;

namespace ProgressBarSimple
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            pb.Value = 3;
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(20);
            timer.Tick += timer_Tick;
            timer.Start();
        }
        void timer_Tick(object sender, EventArgs e)
        {
            pb.Value = pb.Value + 1;
        }
        private void txtEditor_SelectionChanged(object sender, RoutedEventArgs e)
        {
            int row = txtEditor.GetLineIndexFromCharacterIndex(txtEditor.CaretIndex);
            int col = txtEditor.CaretIndex - txtEditor.GetCharacterIndexFromLineIndex(row);
            lblCursorPosition.Text = "Line " + (row + 1) + ", Char " + (col + 1);
        }
    }
}