Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to execute something after a page is rendered not just loaded in wpf

Tags:

c#

wpf

I am trying to get the x,y location of a UI element on a wpf page ( not window). In order to make sure the rendering of the page is completed, I place the revoking of PointToScreen inside the Loaded listener. However i get this runtime exception:

This Visual is not connected to a PresentationSource.

void Page_Loaded(object sender, RoutedEventArgs e)
        {
        .....
         Point position = button1.PointToScreen(new Point(0d, 0d));
        }

Please let me know what to do? Or could you provide an example how I can run dispatcher for this?

like image 578
Waterfr Villa Avatar asked Sep 02 '25 16:09

Waterfr Villa


1 Answers

There's no built-in or official way to do this. However you can use the Dispatcher class as a workaround:

 private void OnWindowLoaded(object sender, RoutedEventArgs e)
 {
     Dispatcher.BeginInvoke(new Action(() => YOUR_THING_HERE), DispatcherPriority.ContextIdle, null);
 }

The dispatcher will run when nearly all other operations are completed (which will include your rendering)

I had a similar problem myself so this answer is based off this blog article that solved it for me.

EDIT: I was actually wrong

There is a ContentRendered event that serves this purpose.

like image 154
Knells Avatar answered Sep 04 '25 06:09

Knells