您可以使用下面介紹的技巧: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