繁体   English   中英

获取鼠标 position 相对于 WPF popup

[英]Get mouse position relative to WPF popup

我有一个绑定到 TextBlock 的 WPF 弹出窗口:

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

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

我尝试了以下方法,但看起来它不起作用:

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

TranslatePoint将相对于 UIElement 的点转换为另一个 UIElement。 在您的示例中,您将获得一个相对于 TextBlock 的点并将其视为相对于弹出窗口并再次将其转换为相对于文本块。 本质上是落后的。

试试这个:

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