当锚元素移动时,如何移动 WPF 弹出窗口? [英] How can I move a WPF Popup when its anchor element moves?

查看:29
本文介绍了当锚元素移动时,如何移动 WPF 弹出窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的弹出窗口:

I have a Popup defined like this:

<Popup
    Name="myPopup"
    StaysOpen="True"
    Placement="Bottom"
    PlacementRectangle="0,20,0,20"
    PlacementTarget="{Binding ElementName=myPopupAnchor}">
    <TextBlock ... />
</Popup>

我为 MouseEnterMouseLeave 事件向 myPopupAnchor 元素添加了事件处理程序.这两个事件处理程序切换弹出窗口的可见性.

I have added event handlers to the myPopupAnchor element for the events MouseEnter and MouseLeave. The two event handlers toggle the popup's visibility.

我的问题是 myPopupAnchor 的位置仅在弹出窗口第一次显示或隐藏然后再次显示时读取.如果锚点移动,则弹出窗口不会.

My problem is the position of myPopupAnchor is only read when the popup is first shown, or hidden and then shown again. If the anchor moves, the popup does not.

我正在寻找解决此问题的方法,我想要一个移动的弹出窗口.我可以通知 WPF PlacementTarget 绑定已更改并应再次读取吗?我可以手动设置弹出窗口的位置吗?

I'm looking for ways to work around this, I want a moving Popup. Can I notify WPF that the PlacementTarget binding has changed and should be read again? Can I manually set the popup's position?

目前,我有一个非常粗略的解决方法,包括关闭然后再次打开弹出窗口,这会导致一些重新绘制问题.

Currently, I have a very crude workaround that involves closing and then opening the popup again, which causes some repainting issues.

推荐答案

我查看了一些选项和示例.对我来说似乎最有效的方法是碰撞"导致 Popup 自行重新定位的属性之一.我使用的属性是 Horizo​​ntalOffset.

I looked at a couple options and samples out there. The thing that seems to work best for me is to "bump" one of the properties that causes the Popup to reposition itself on its own. The property that I used is HorizontalOffset.

我将其设置为(自身 + 1),然后将其设置回原始值.我在重新定位窗口时运行的事件处理程序中执行此操作.

I set it to (itself + 1) and then set it back the original value. I do this in an event handler that runs when the window is repositioned.

// 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;
    };
}

当窗口移动时,弹出窗口将重新定位.Horizo​​ntalOffset 的细微变化没有被注意到,因为无论如何窗口和弹出窗口已经在移动.

When the window is moved, the popup will reposition. The subtle change in the HorizontalOffset is not noticed because the window and popup are already moving anyway.

我仍在评估弹出控件是否是在其他交互期间控件保持打开状态的最佳选择.我在想 Ray Burns 建议将这些东西放在装饰层在某些情况下似乎是一种不错的方法.

I'm still evaluating whether a popup control is the best option in cases where the control stays open during other interaction. I'm thinking that Ray Burns suggestion to put this stuff in an Adorner layer seems like a good approach for some scenarios.

这篇关于当锚元素移动时,如何移动 WPF 弹出窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆