使用PointToScreen在WPF中查找控件的位置 [英] Find location of a control in wpf using PointToScreen

查看:241
本文介绍了使用PointToScreen在WPF中查找控件的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在主窗口中找到用户控件的相对坐标.我尝试使用"Control.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:此视觉未连接到PresentationSource

我认为这与我在正确呈现视觉效果之前调用pointToScreen有关,因为我已经在我的Mains构造函数中调用了该方法.

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.

只是要弄清楚我要做什么,我的控件包含一个光电控件,我需要在我的maincontrol内放置确切的位置,因为我想使用这些坐标在顶部创建一个控件的副本它

使用PointToScreen进行实验.

Experimenting with PointToScreen.

推荐答案

在代码中注册UserControl的Loaded事件. 这应该可以解决当您尝试获得位置时尚未呈现视觉效果的错误.

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

这篇关于使用PointToScreen在WPF中查找控件的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆