Poma
Poma

Reputation: 8484

How to preload XAML at app startup?

I have pretty large UserControl that's not showed at main screen, but user almost always uses it later. It takes some time to load for the first time (parse BAML etc.) then other instances are constructed pretty fast. The question is how to make it to preload at app startup during splash screen?

My idea was to construct usused instance at startup:

void Startup()
{
    //....
    new MyCustomControl();
    //....
} 

but then I have to deal with special case construction (it's does not have default constructor with no args). I think there should be more convenient way.

Upvotes: 5

Views: 1870

Answers (2)

Vinit Sankhe
Vinit Sankhe

Reputation: 19895

To preload complex UIs so that they take less time when they are actually "viewed" on the screen, we would have to follow following steps...

  1. Make it load in Invisible mode. Change all you bindings to visibility trigger based. This way UI thread would neither block nor take time to perform the rendering in invisible mode.

    <Style TargetType="TextBlock">
            <Style.Triggers>
                    <Trigger Property="IsVisible" Value="True">
                            <Setter Property="Text" Value="{Binding Value}"/>
                    </Trigger>
            </Style.Triggers>
    </Style>
    
  2. Separate the data context (viewmodel) loading from the UI loading. What this means is any data represented by the user control can be loaded on worker thread and then the UI must be notified using Dispatcher.BeginInvoke(). Make sure that this happens when UI is visible otherwise the bindings would take effect due to step 1.

  3. When the UI is actually "viewed", choreograph the loading of UI's regions ... e.g. Use Expanders and collapse them by default... but when the UI is viewed, start sliding the expander using sliding animation and content opacity animation to show the contents inside it etc...

IN our application we employed such techniques to achieve complex UIs to load fast and be responsive. One such UI which was a geographical map when viewed would not only block the UI thread but also take 20 seconds to load. Using above steps the loading was reduced to 4 seconds and no blocking ocurred of the UI thread.

I hope these steps will help you too.

Upvotes: 3

paparazzo
paparazzo

Reputation: 45106

You could use the App ctor or Startup

    App()
    {
        System.Diagnostics.Debug.WriteLine("App ctor");
        //ctor
    }

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("App Startup");
    }

Upvotes: 0

Related Questions