#1,029 – Simple ProgressBar Example

Here’s an example of how we could use a ProgressBar in an application to show # records processed.

        <ProgressBar Value="{Binding NumRecsLoaded}" Maximum="{Binding TotalNumRecs}"
                     Height="15" Margin="15,15,15,0"/>
        <Label Content="{Binding RecsLoadedMessage}"
        <Button Margin="15" Padding="15,3" HorizontalAlignment="Center"
            Content="Start" Click="Button_Click"/>

In code, we declare properties for total number of records and number already loaded. When the user clicks on the Button, we set up a timer that increments the # records loaded each time that it ticks (twice a second).  (Note–to use the DispatcherTimer, you need to use namespace System.Windows.Threading).

    public partial class MainWindow : Window, INotifyPropertyChanged
        private int numRecsLoaded = 0;
        public int NumRecsLoaded
            get { return numRecsLoaded; }
            protected set
                numRecsLoaded = value;

        private int totalNumRecs = 12;
        public int TotalNumRecs
            get { return totalNumRecs; }
            protected set
                totalNumRecs = value;

        public string RecsLoadedMessage
            get { return string.Format("Loaded {0} records...", numRecsLoaded);  }

        public MainWindow()
            this.DataContext = this;


        // INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropertyChanged(string propName)
            PropertyChanged(this, new PropertyChangedEventArgs(propName));

        private void Button_Click(object sender, RoutedEventArgs e)
            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += (s,ea) =>
                if (NumRecsLoaded == TotalNumRecs)
            timer.Interval = new TimeSpan(0, 0, 0, 0, 500);  // 2/sec



About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: