I'm trying to make a "loading" overlay to show when my program is fetching the data from the online DB.

The loading happens at the very beginning (when it boots) but I'm having some issues to show my overlay.

It seems like the layout isn't being shown at the moment when my data gets fetched and thus it's impossible to show the overlay.

My guess is that the elements would be shown after the "InitializeComponent()" method, but that doesn't seem to be the case.

public MainWindow()
    {
        InitializeComponent();
        Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        this.DataContext = new MainViewModel();
        OverlayLoading.Visibility = Visibility.Hidden;
    }

Important: the data gets fetched in the constructor of the MainViewModel (I'm using MVVM)

Help would be appreciated!

有帮助吗?

解决方案

You're fetching the data on the UI thread, which will block the UI until the data is retrieved, by which time you no longer need to display the overlay at all.

What you need to do is fetch the data from a different thread, thus allowing the UI to display the loading overlay while the action is being performed. You should have a look at BackgroundWorker - it knows how to handle these kind of scenarios pretty well (these scenarios being performing an operation on a background thread and allowing to update the UI while keeping it responsive).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top