Search code examples
c#wpfbackgroundworkersplash-screen

Updating WPF window labels while loading a new window


I have tried everything including the Background Worker and Dispatcher and I cannot figure out how to do this.

Here is what I am trying to accomplish.

My WPF 'MainWindow' has a series of functions it completes before it renders. It takes a total of 20 seconds to complete. Because of this, I have created a window called 'LoadWindow'. I have the 'LoadWindow' ContentRendered event set to load my 'MainWindow' and then close itself upon completion. I basically have created a SplashScreen.

 private void Window_ContentRendered(object sender, EventArgs e)
 {
     MainWindow mainWindow = new MainWindow();
     mainWindow.Show();
     this.Close();
 }

I would like one of my labels, let's call it 'splashLabel' to update as each function is fired in my 'MainWindow' code behind. these functions are called during my grids layoutRoot Initialize event. As I currently have it my splashLabel will not render even the though content has been changed.

 private void layOutRoot_Initialized(object sender, EventArgs e)
 {
     LoadWindow.splashLabel.content = "Function 1";
     Function1();
     LoadWindow.splashLabel.content = "Function 2";
     Function2();
     LoadWindow.splashLabel.content = "Function 3";
     Function3();
 }

Please point me in the right direction! My days of googling have not helped.


Solution

  • Taking a step back, you've got a slow loading window which you want to report progress on?

    If so, what I have found to work well in the past is to add an overlay to your control which hides all your content and has a label on it to report status. Bind the visibility of that to an IsBusy property. Bind your label to a Status property.

    Then in your view model, assuming MVVM, define your functions as async. Then write a simple function which calls these in turn and updates the properties mentioned. Something like...

    Private async void DoLoadingTasks()
    {
         IsBusy = true;
         await Function1();
         Status = "step complete";
         ....
         IsBusy = false;
    }
    

    Call that method from your view model constructor and you should have a responsive UI and notifications of progress.

    Does that do what you want?