“父窗口拖动的时候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>

本文的示例工程可以从附件下载。

欢迎各种转载,转载请注明来自 Leaco 的博客http://www.cnblogs.com/Leaco/p/3168540.html

转载于:https://www.cnblogs.com/Leaco/p/3168540.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值