Find location of a control in wpf using PointToScreen

我只是一个虾纸丫 提交于 2019-12-10 21:49:30

问题


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.


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/24802945/find-location-of-a-control-in-wpf-using-pointtoscreen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!