您可以使用下面介绍的技巧:http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/27950e73-0007-4e0b-9f00-568d2db1d979
我创建了一个Blend behavior,可以很容易与任何弹出使用:
/// <summary>
/// A behavior that forces the associated popup to update its position when the <see cref="Popup.PlacementTarget"/>
/// location has changed.
/// </summary>
public class AutoRepositionPopupBehavior : Behavior<Popup> {
public Point StartPoint = new Point(0, 0);
public Point EndPoint = new Point(0, 0);
protected override void OnAttached() {
base.OnAttached();
if (AssociatedObject.PlacementTarget != null) {
AssociatedObject.PlacementTarget.LayoutUpdated += OnPopupTargetLayoutUpdated;
}
}
void OnPopupTargetLayoutUpdated(object sender, EventArgs e) {
if (AssociatedObject.IsOpen) {
ResetPopUp();
}
}
public void ResetPopUp() {
// The following trick that forces the popup to change it's position was taken from here:
// http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/27950e73-0007-4e0b-9f00-568d2db1d979
Random random = new Random();
AssociatedObject.PlacementRectangle = new Rect(new Point(random.NextDouble()/1000, 0), new Size(75, 25));
}
}
下面是一个例子如何应用行为:
<Popup ...>
<i:Interaction.Behaviors>
<Behaviors:AutoRepositionPopupBehavior />
</i:Interaction.Behaviors>
</Popup>
感谢您的回答,我已经实现了这个行为,但有时候'OnPopupTargetLayoutUpdated'没有触发(例如当我移动窗口时),任何建议蒸发散? – Bolu 2011-03-17 14:11:43
只是为了那里的新手,你需要设置你的弹出窗口的放置目标。感谢PG,这个工作非常好。 – 2014-07-17 16:01:50