Question

I have two wpf windows in my wpf application.

1) When i click on the load button it loads the second Window. The secong window takes 15 to 20 secs to load.

How do i add a progress bar to show a loading window and when the second window loads close the progress bar.

Was it helpful?

Solution

I was recently working on a loading window for my app where you click the app and it takes about 10s to load. I have a loading window with an intermediate loading bar. The key was to put the loading window in a different thread to enable the animation to run while it was loading the other window on the main thread. The problem was to make sure we do stuff propertly (like when we close we close the window should stop the thread... etc).

In the code below... LoadingWindow is a small window with a progress bar on it, SecondWindow would be the window that is slow to load.

    public void OnLoad()
    {
        Dispatcher threadDispacher = null;

        Thread thread = new Thread((ThreadStart)delegate
        {
            threadDispacher = Dispatcher.CurrentDispatcher;
            SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(threadDispacher));

            loadingWindow = new LoadingWindow();
            loadingWindow.Closed += (s, ev) => threadDispacher.BeginInvokeShutdown(DispatcherPriority.Background);
            loadingWindow.Show();

            System.Windows.Threading.Dispatcher.Run();
        });

        thread.SetApartmentState(ApartmentState.STA);
        thread.IsBackground = true;
        thread.Start();

        // Load your second window here on the normal thread
        SecondWindow secondWindow = new SecondWindow();

        // Presumably a slow loading task            

        secondWindow.Show();

        if (threadDispacher != null)
        {
            threadDispacher.BeginInvoke(new Action(delegate
                {
                    loadingWindow.Close();
                }));
        }
    }

OTHER TIPS

There are many ways you can accomplish that. An easy way would be to create a third window or panel with the progress bar or a waiting animation. That third window is in charge of loading your second window and get displayed as soon as you click the load button on the first window. When loading of the second window is completed, the third window with the progress bar closes and the second window gets displayed.

hope this helps.

You could use the BusyIndicator as part of the WPF extended toolkit. You can download it here: http://wpftoolkit.codeplex.com/wikipage?title=BusyIndicator

On immediate loading of the new window before you do your expensive processing that takes forever, you can set the IsBusy to true. When processing is done, set IsBusy back to false. This method involves wrapping your XAML in the BusyIndicator in the 2nd window, which may or may not be what you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top