Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pre-render a view?

Tags:

wpf

xaml

My ViewModel selects a view based on user click. One of the views contains a lot of visual elements - viewmodels with datatemplates that contain viewmodels with datatemplates, each one renders on a canvas with a background imagebrush. The full view ends with approx 100 of these canvas brushes, each one with a dozen ellipses superimposed, and the whole view is in a scrollable viewbox.

The first time this view is created, user clicks then hangs around for some time while it's all rendered. I'd like to get this rendering done earlier - for example during startup. I've created the view object, but still when the user clicks we're hanging around while the rendering is done.

Is there any way to get WPF/xaml to pre-render it so the click response is better?

like image 354
AndyC Avatar asked Oct 06 '22 18:10

AndyC


1 Answers

As I see you are using MVVM pattern. I would try following aproach:

Create the view during startup and also set its DataContext to your viewmodel instance. Then simulate the work WPF performs. Call Measure() and Arrange() methods on the view to force WPF to update data binding and generate visual tree.

But there is only one UI thread. So at this point blocks your startup routine again. You could avoid this by splitting the "work" in smaller pieces. Maybe you have some collection of items in your view model. Then you can use DipatcherTimer and in each step add some reasonable amount of items to the collection and call Measure and Arrange after each iteration to update the visual tree of the view. After the view is fully initialized, the rendering shouldn't block any more.

like image 162
Lubo Avatar answered Oct 10 '22 03:10

Lubo