我们用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 += delegate28 {29 var offset = pop.HorizontalOffset;30 pop.HorizontalOffset = offset + 1;31 pop.HorizontalOffset = offset;32 };33 }34 }35 }36 37 }
之后只需要在Popup控件上这样写即可:
12 3 4
本文的示例工程可以从下载。
欢迎各种转载,转载请注明来自 Leaco 的博客: