解决popup不随着window一起移动的问题

参考:

http://stackoverflow.com/questions/1600218/how-to-move-a-wpf-popup

http://social.msdn.microsoft.com/Forums/zh-CN/wpfzhchs/thread/2616e607-3954-4bfd-ae29-e0d813263030

给窗口加一个“LocationChanged”事件,然后在这个事件中做如下处理:

1 private void window_LocationChanged(object sender, EventArgs e)
2 
3 {
4 
5     this.TestPopup.ClearValue(Popup.IsOpenProperty);
6 
7     this.TestPopup.IsOpen = true;
8 
9 }
public MainWindow()
{

 LocationChanged += new EventHandler(MainWindow_LocationChanged);

 }

 

void MainWindow_LocationChanged(object sender, EventArgs e)

{

//参考链接1

var mi = typeof(Popup).GetMethod("UpdatePosition", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

mi.Invoke(popBottom, null);

 

//此方法容易导致 闪烁

//popBottom.ClearValue(Popup.IsOpenProperty);

 //popBottom.IsOpen = true;

}
 

 方法2:转载于Leaco 的博客http://www.cnblogs.com/Leaco/p/3168540.html

 1 public class PopopHelper
 2     {
 3         public static DependencyObject GetPopupPlacementTarget(DependencyObject obj)
 4         {
 5             return (DependencyObject)obj.GetValue(PopupPlacementTargetProperty);
 6         }
 7 
 8         public static void SetPopupPlacementTarget(DependencyObject obj, DependencyObject value)
 9         {
10             obj.SetValue(PopupPlacementTargetProperty, value);
11         }
12 
13         // Using a DependencyProperty as the backing store for PopupPlacementTarget.  This enables animation, styling, binding, etc...
14         public static readonly DependencyProperty PopupPlacementTargetProperty =
15             DependencyProperty.RegisterAttached("PopupPlacementTarget", typeof(DependencyObject), typeof(PopopHelper), new PropertyMetadata(null,OnPopupPlacementTargetChanged));
16 
17         private static void OnPopupPlacementTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
18         {
19             if (e.NewValue != null)
20             {
21                 DependencyObject popupPopupPlacementTarget = e.NewValue as DependencyObject;
22                 Popup pop = d as Popup;
23 
24                 Window w = Window.GetWindow(popupPopupPlacementTarget);
25                 if (null != w)
26                 {
27                     w.LocationChanged += delegate
28                     {
29                         var offset = pop.HorizontalOffset;
30                         pop.HorizontalOffset = offset + 1;
31                         pop.HorizontalOffset = offset;
32                     };
33                 }
34             }
35         }
36         
37     }

然后在Popup控件上这样写即可:

1 <Grid>
2         <TextBox x:Name="placementTextBox"/>
3        <Popup PopopHelper.PopupPlacementTarget="{Binding ElementName=placementTextBox}" />
4    </Grid>

 

原文地址:https://www.cnblogs.com/MarcLiu/p/3688166.html