0

In WPF I have Window with some buttons. Currently I have this functionality: I click a button and the Popup pops underneath the button.

My goal is when dragging main Window the Popup to move with the Window so Popup remains under the button.

Currently I'm using this code, but it seems it's not working - Popup pops, but when dragging main Window the Popup stays in the same place.

Here is my code:

    private void Window_LocationChanged(object sender, EventArgs e)
    {
        ResetPopUp();
    }

    private void ResetPopUp()
    {
        var offsetHor = popup.HorizontalOffset;
        var offsetVer = popup.VerticalOffset;

        popup.HorizontalOffset = offsetHor + 1;
        popup.HorizontalOffset = offsetHor - 1;

        popup.VerticalOffset = offsetVer + 1;
        popup.VerticalOffset = offsetVer - 1;
    }

I will be thankfully for any answers!

  • 1
    Does this answer your question? [How can I move a WPF Popup when its anchor element moves?](https://stackoverflow.com/questions/1600218/how-can-i-move-a-wpf-popup-when-its-anchor-element-moves) – Klaus Gütter Jan 12 '22 at 08:27

2 Answers2

1

Here is what we use in our code. Maybe it can help.

    public MainWindow()
    {
        this.InitializeComponent();
        this.SizeChanged += delegate { this.ResetPopupLocation(); };

        this.LocationChanged += delegate { this.ResetPopupLocation(); };
    }

    private static IEnumerable<Popup> GetOpenPopups()
    {
        return PresentationSource.CurrentSources.OfType<HwndSource>()
            .Select(h => h.RootVisual)
            .OfType<FrameworkElement>()
            .Select(f => f.Parent)
            .OfType<Popup>()
            .Where(p => p.IsOpen);
    }

    private void ResetPopupLocation()
    {
        foreach (var popup in GetOpenPopups())
        {
            var offset = popup.HorizontalOffset;
            popup.HorizontalOffset = offset + 1;
            popup.HorizontalOffset = offset;
        }
    }

    
Allen Shen
  • 39
  • 2
-2

you can combine PlacementTarget and Placement properties of popup to achieve it's positioning relative/centered to it's parent

something like below if you want the popup position at center of parent

        <Popup
            PlacementTarget="{Binding ElementName = "parent_container_windowname"}"
            Placement="Center">
        </Popup>

if you want the placement of popup at top left corner of parent then you could use Placement="Relative"

GSM
  • 87
  • 11