解決WPF下popup不隨着window一起移動的問題

轉自: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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章