I know this has been asked before (Get Absolute Position of element within the window in wpf) but I haven’t been able to implement properly yet. I’m trying to have a child window open up relative to the control in the parent window. So far, I have this;
messageWindow = new Message(true);
Point relativePoint = btn1.TransformToAncestor(this).Transform(new Point(0, 0));
messageWindow.Left = relativePoint.X;
messageWindow.Top = relativePoint.Y;
messageWindow.Show();
Now although this does effect the position of the child window (messageWindow), it doesn’t seem to place it on/beside the btn1 control in the parent. Another problem I have with it is that if I move the parent window, then recall this method having closed the original messageWindow the new instance of the window displays in the old position (even though btn1 is in a new position). I find this odd and was wondering if anyone could help me fix this.
UPDATE
Thanks to Charleh for explaining that I was only setting them relative to the control location in the window, not to the overall screen. So now it is a question of getting the parent window’s location on the screen and adding it to the XY also. How would I get this? Just tried this code (although I’ll be honest, I don’t quite understand it) bus still doesn’t seem to follow very closely. What’s a good way of getting Window location on the screen?;
messageWindow= new Message(true);
Point relativePoint = btn1.TransformToAncestor(this).Transform(new Point(0, 0));
PresentationSource ScreenPos = PresentationSource.FromVisual(this);
messageWindow.Left = relativePoint.X + (96.0 * ScreenPos.CompositionTarget.TransformToDevice.M11);
messageWindow.Top = relativePoint.Y + (96.0 * ScreenPos.CompositionTarget.TransformToDevice.M22);
messageWindow.Show();
relativePointis the position of the control relative to theWindow, not the screen. When setting theLeftandRightpoints ofmessageWindow(the child window), the points are relative to the screen, not the parent window.In order to get the correct position, you’ll need to find the position of the parent window and then do some math to find where the control is located relative to the screen, not the window which should give you the location of where you want to place the child window.