Search code examples
wpfxamlpopup

WPF Popup placement relative to main window


I have a WPF application that uses one window as main window. Now I want to display various popups centered in the window. This works fine when the popup is placed inside the window. However, I have implemented the popups as user control; meaning that the main window contains a user controls which itself contains the actual popup. So the UI element tree looks like this:

Window --> UserControlPopup --> Popup

The popup inside the user control is declared like this:

<UserControl x:Class="X.Custom_Controls.ErrorPopup"
         ...
         xmlns:local="clr-namespace:X.Custom_Controls"
         mc:Ignorable="d" d:DesignHeight="360" d:DesignWidth="500">

<Popup Name="errorPopup" Height="360" Width="500" Placement="Center" StaysOpen="True" PlacementTarget="{Binding ElementName=mainWindow}">
    ...
</Popup> </UserControl>

The mainWindow element name is the one of my main window, which is declared as follows:

<Window x:Class="X.MainWindow" x:Name="mainWindow" ...>

The problem is that the popup is not placed in the center, but on the left side. So my guess is that the popup cannot resolve the elementName properly (since it's a child of a child of the mainWindow). Does anyone know how I can solve this issue in XAML?

Update: the solution was to use

PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType=Window}}"

Solution

  • The solution was to use the following as PlacementTarget:

    PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType=Window}}"