简体   繁体   English

获取鼠标 position 相对于 WPF popup

[英]Get mouse position relative to WPF popup

I have a WPF Popup bound to a TextBlock:我有一个绑定到 TextBlock 的 WPF 弹出窗口:

<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.当鼠标进入 TextBlock 时,我想从代码隐藏中获取鼠标 position (X,Y),然后将其转换为相对于打开的弹出窗口的新 position (X,Y)。

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. TranslatePoint将相对于 UIElement 的点转换为另一个 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.在您的示例中,您将获得一个相对于 TextBlock 的点并将其视为相对于弹出窗口并再次将其转换为相对于文本块。 Essentially it is backward.本质上是落后的。

Try this:试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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