Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find location of a control in wpf using PointToScreen

Tags:

c#

wpf

point

I'm trying to find my relative coordinate for a usercontrol inside my mainwindow. I tried using the "Control.PointToScreen()" method but with no luck. Everytime I do this i get an exception that says:

System.InvalidOperationException: This Visual is not connected to a PresentationSource

I think this has something to do with me calling pointToScreen before the visuals have rendered properly, since i'm already calling the method in my Mains Constructor.

Anyways, I would like to hear if anyone of you had a hint/Solution/Idea how I could perhaps work around this.

Just to clearify what i'm trying to do, my control contains a photocontrol which i need the exact location off inside my maincontrol, since i want to use these coordinates to create a duplicate of the control on top of it

Experimenting with PointToScreen.

like image 702
Max Mazur Avatar asked Dec 12 '22 04:12

Max Mazur


2 Answers

In your code register for the Loaded event of the UserControl. That should fix the bug that the visuals have not been rendered yet when you try to get the position.

YourControl.Loaded += ControlLoaded;

public void ControlLoaded(object sender, EventArgs e){
    Console.WriteLine(YourControl.PointToScreen(new Point(0,0));
}

Edit

Since you want the position of your control relative to your window, better try that one .

YourControl.TransformToAncestor(YourWindow).Transform(new Point(0,0))
like image 76
sebhaub Avatar answered Jan 21 '23 13:01

sebhaub


Since Contend rendered didn't work I found a solution for my problem.

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
  ItemsControl ItemsControl = UCEnvironmentControl.GetItemsControlPhotos();
  Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => Control.PointToScreen(new Point(0,0));
}

This way, it fires in the LoadedEvent, but waits for the content to be rendered, and then finally it gives you your coordinate back and sets your control

like image 44
Max Mazur Avatar answered Jan 21 '23 11:01

Max Mazur