Wait until control layout is finished

I have had a related situation: I have a print preview dialog that creates a fancy rendering. Normally, the user will click a button to actually print it, but I also wanted to use it to save an image without user involvement. In this case, creating the image has to wait until the layout is complete.

I managed that using the following:

Dispatcher.Invoke(new Action(() => {SaveDocumentAsImage(....);}), DispatcherPriority.ContextIdle);

The key is the DispatcherPriority.ContextIdle, which waits until background tasks have completed.

Edit: As per Zach's request, including the code applicable for this specific case:

Dispatcher.Invoke(() => { richTextBox.ScrollToEnd(); }), DispatcherPriority.ContextIdle);

I should note that I'm not really happy with this solution, as it feels incredibly fragile. However, it does seem to work in my specific case.


Have a look at UpdateLayout

especially:

Calling this method has no effect if layout is unchanged, or if neither arrangement nor measurement state of a layout is invalid

So calling InvalidateMeasure or InvalidateArrange, depending on your needs should work.

But considering your piece of code. I think that won't work. Alot of WPF loading and creating is deffered, so adding something to Document.Blocks does not necesarilly change the UI directly. But i must say, this is just a guess and maybe i'm wrong.