轉自:https://www.cnblogs.com/zhidanfeng/articles/6882869.html
當我們設定Popup的StayOpen=”True”時,會發現移動窗體或者改變窗體的Size的時候,Popup并不會跟随着一起移動位置。為了解決這個問題,可以給Popup定義一個附加屬性,代碼如下所示:
/// <summary>
/// Popup幫助類,解決Popup設定StayOpen="True"時,移動窗體或者改變窗體大小時,Popup不随窗體移動的問題
/// </summary>
public class PopopHelper
{
public static DependencyObject GetPopupPlacementTarget(DependencyObject obj)
{
return (DependencyObject)obj.GetValue(PopupPlacementTargetProperty);
}
public static void SetPopupPlacementTarget(DependencyObject obj, DependencyObject value)
{
obj.SetValue(PopupPlacementTargetProperty, value);
}
public static readonly DependencyProperty PopupPlacementTargetProperty =
DependencyProperty.RegisterAttached("PopupPlacementTarget", typeof(DependencyObject), typeof(PopopHelper), new PropertyMetadata(null, OnPopupPlacementTargetChanged));
private static void OnPopupPlacementTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null)
{
DependencyObject popupPopupPlacementTarget = e.NewValue as DependencyObject;
Popup pop = d as Popup;
Window w = Window.GetWindow(popupPopupPlacementTarget);
if (null != w)
{
//讓Popup随着窗體的移動而移動
w.LocationChanged += delegate
{
var mi = typeof(Popup).GetMethod("UpdatePosition", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
mi.Invoke(pop, null);
};
//讓Popup随着窗體的Size改變而移動位置
w.SizeChanged += delegate
{
var mi = typeof(Popup).GetMethod("UpdatePosition", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
mi.Invoke(pop, null);
};
}
}
}
}
使用方法:
<Popup x:Name="PART_Popup" AllowsTransparency="True" IsOpen="True" Placement="Bottom"
PlacementTarget="{Binding ElementName=PART_ToggleButton}"
HorizontalOffset="-5"
ZUI:PopopHelper.PopupPlacementTarget="{Binding ElementName=PART_ToggleButton}"
StaysOpen="True">
<Border x:Name="ItemsPresenter" Background="Transparent">
<ItemsPresenter />
</Border>
</Popup>