WPF – Loading Spinner Via MVVM and Attached Properties

wpf loading spinner

When I used to write a lot of Ajax for ASP.NET (many years ago) I quite like the feature whereby you could disable the page and show a ‘loading spinner’ while waiting for an update in the page.
This is a great feature to have in WPF, so I have created a ViewModel with a ‘loading’ switch (bool), and an attached property that creates and displays the animated spinner (for the duration of the switch flag being true)
Firstly, we need a control template for a content control that will be our animated spinner.

The Content property of out content presenter will include our text message that will be inside the spinner
Next we need our attached property class

Now our ViewModel

Heres out Window that uses the attached property to include a spinner

And finally our code behind

Before we run the spinner

Spinner running

Spinner finished

About the author

Dean Chalk

I am a freelance (contract) Microsoft WPF developer, specialising in challenging, high-performance user interface development. I have been working exclusively on enterprise WPF app development since 2006, and I have been a part of some of the most demanding WPF projects ever created withing the Investment Banking / trading industry.

  • Jason says:

    I like your spinner and have been using a version of it in a custom window control for a number of years.

    One of the modifications I made was to add the option for a cancel button, but I am having difficulty actually implementing the cancel.

    My “Load” method makes a number of long database queries on separate threads using the parallel Task class. When the Tasks complete the results are joined back to UI thread using Dispatcher.

    All of this works, but I am having a tough time finding a good way to abandon the threads and clearing the spinner if the user hits the Cancel button.

    Any thoughts?


  • >