WPFの下でpopupがwindowと一緒に移動しない問題を解決する


変換元:https://www.cnblogs.com/zhidanfeng/articles/6882869.html
PopupのStayOpen="True"を設定すると、フォームを移動したり、フォームのSizeを変更したりすると、Popupは一緒に位置を移動しません.この問題を解決するために、Popupに次のような追加属性を定義できます.
/// 
/// Popup   ,  Popup  StayOpen="True" ,             ,Popup         
/// 
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>