简体   繁体   中英

Get mouse position relative to WPF popup

I have a WPF Popup bound to a TextBlock:

<TextBlock x:Name="MyTextBlock" Text="Hello" MouseEnter="PlacementTarget_MouseEnter" MouseLeave="PlacementTarget_MouseLeave"/>
<Popup x:Name="MyPopup" PlacementTarget = "{Binding ElementName=MyTextBlock}"/>

From code-behind I want to get the mouse position (X,Y) when mouse enters in TextBlock and then translate it to a new position (X,Y) relative to the popup that is opened.

I have tried the following but it looks like it is not working:

Point mousePosition = Mouse.GetPosition((UIElement)MyTextBlock);
Point newPoint = MyPopup.TranslatePoint(mousePosition, MyTextBlock);

TranslatePoint translates a point relative to the UIElement to another UIElement. In your example you are getting a point relative to the TextBlock and treating it as if it were relative to the popup and translating it to relative to the textblock again. Essentially it is backward.

Try this:

Point mousePosition = Mouse.GetPosition((UIElement)MyTextBlock);
Point newPoint = MyTextBlock.TranslatePoint(mousePosition, MyPopup);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM