XAML 获取相对于WPF弹出菜单的鼠标位置

7uhlpewt  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(165)

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

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

从代码隐藏中,我希望在鼠标进入TextBlock时获得鼠标位置(X,Y),然后将其转换为相对于打开的弹出窗口的新位置(X,Y)。
我尝试了以下方法,但似乎不起作用:

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

e0bqpujr1#

TranslatePoint将相对于UIElement的点转换为另一个UIElement。在您的示例中,您将获取相对于TextBlock的点,并将其视为相对于弹出窗口,然后将其再次转换为相对于文本块的点。实际上,这是向后转换。
试试这个:

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

相关问题