Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...