我有一个像这样定义的弹出窗口:
<Popup
Name="myPopup"
StaysOpen="True"
Placement="Bottom"
PlacementRectangle="0,20,0,20"
PlacementTarget="{Binding ElementName=myPopupAnchor}">
<TextBlock ... />
</Popup>
我已向 myPopupAnchor
元素添加了事件 MouseEnter
和 MouseLeave
的事件处理程序。这两个事件处理程序切换弹出窗口的可见性。
我的问题是 myPopupAnchor 的位置仅在弹出窗口首次显示或隐藏然后再次显示时读取。如果 anchor 移动,弹出窗口不会移动。
我正在寻找解决此问题的方法,我想要一个移动的弹出窗口。我可以通知 WPF PlacementTarget
绑定(bind)已更改并应重新读取吗?我可以手动设置弹出窗口的位置吗?
目前,我有一个非常粗略的解决方法,涉及关闭然后再次打开弹出窗口,这会导致一些重画问题。
最佳答案
我查看了几个选项和示例。对我来说最有效的方法是“碰撞”导致弹出窗口自行重新定位的属性之一。我使用的属性是 HorizontalOffset。
我将其设置为(本身+1),然后将其设置回原始值。我在重新定位窗口时运行的事件处理程序中执行此操作。
// Reference to the PlacementTarget.
DependencyObject myPopupPlacementTarget;
// Reference to the popup.
Popup myPopup;
Window w = Window.GetWindow(myPopupPlacementTarget);
if (null != w)
{
w.LocationChanged += delegate(object sender, EventArgs args)
{
var offset = myPopup.HorizontalOffset;
myPopup.HorizontalOffset = offset + 1;
myPopup.HorizontalOffset = offset;
};
}
当窗口移动时,弹出窗口将重新定位。 HorizontalOffset 中的细微变化不会被注意到,因为窗口和弹出窗口已经在移动。
我仍在评估弹出控件是否是在其他交互期间控件保持打开状态的情况下的最佳选择。我想 Ray Burns suggestion to put this stuff in an Adorner layer对于某些场景来说似乎是一个好方法。
关于wpf - 当 anchor 元素移动时,如何移动 WPF 弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1600218/