Max Mazur
Max Mazur

Reputation: 1316

Find location of a control in wpf using PointToScreen

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.

Upvotes: 5

Views: 15504

Answers (3)

volta
volta

Reputation: 53

The solution from Max Mazur is working for me:

public partial class MainWindow : Window
    {
        Point locationOfYourControl;

        public MainWindow()
        {
                InitializeComponent();
                this.ContentRendered += MainWindow_ContentRendered;
        }

        private void MainWindow_ContentRendered(object sender, EventArgs e)
        {
            locationOfYourControl = YourControl.PointToScreen(new Point(0, 0));
        }
    }

Upvotes: 0

Max Mazur
Max Mazur

Reputation: 1316

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

Upvotes: 2

sebhaub
sebhaub

Reputation: 734

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))

Upvotes: 11

Related Questions