使用PointToScreen在WPF中查找控件的位置

编程入门 行业动态 更新时间:2024-10-14 12:25:56
本文介绍了使用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中查找控件的位置

本文发布于:2023-11-07 00:06:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控件   位置   PointToScreen   WPF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!