我們用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