“父窗口拖动的时候Popup不随着父窗口移动”问题的解决方案

我们用WPF用的Popup时候会发现,当 StaysOpen=True 的时候,因为Popup不会消失,在父窗口移走的时候Popup仍旧在原地。。。作者在国外网站上无意间发现了这个解决方案,拿出来给大家分享:

方法是为Popup定义一个附加属性。代码如下。

复制代码
 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>
posted @ 2021-03-01 15:39  honeys  阅读(127)  评论(0编辑  收藏  举报