WPF弹出窗口相对于主窗口的位置

WPF弹出窗口相对于主窗口的位置,wpf,xaml,popup,placement,Wpf,Xaml,Popup,Placement,我有一个WPF应用程序,它使用一个窗口作为主窗口。现在我想在窗口中央显示各种弹出窗口。当弹出窗口放置在窗口内时,此功能正常工作。但是,我实现了弹出窗口作为用户控件;这意味着主窗口包含一个用户控件,该控件本身包含实际的弹出窗口。因此,UI元素树如下所示: Window --> UserControlPopup --> Popup 用户控件内的弹出窗口声明如下: <UserControl x:Class="X.Custom_Controls.ErrorPopup"

我有一个WPF应用程序,它使用一个窗口作为主窗口。现在我想在窗口中央显示各种弹出窗口。当弹出窗口放置在窗口内时,此功能正常工作。但是,我实现了弹出窗口作为用户控件;这意味着主窗口包含一个用户控件,该控件本身包含实际的弹出窗口。因此,UI元素树如下所示:

Window --> UserControlPopup --> Popup
用户控件内的弹出窗口声明如下:

<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>

尝试通过
x:Reference
访问主窗口。这一条应该有效:

<MainWindow x:Name="mainWindow">
    <UserControl Tag="{x:Reference mainWindow}">
</MainWindow>
<UserControl x:Name="userControl">
<PopUp PlacementTarget="{Binding Path=Tag, ElementName=userControl}"/>
</UserControl>


通过这种方式,您可以在另一个控件/UserControls中使用您的UserControl,而无需修改它,只需从外部设置标记属性,如果您使用{RelativeSource AncestorType=Window},则需要修改它。

您尝试过相对源吗
PlacementTarget=“{Binding RelativeSource={RelativeSource AncestorType=MainWindow}}”
“MainWindow”无法工作,因为WPF无法识别该类型。但是,对于“Window”,它可以工作:PlacementTarget=“{Binding RelativeSource={RelativeSource AncestorType=Window}”。谢谢Nope不工作,在运行时抛出“System.Windows.Markup.XamlParseException”(“无法解析引用”)。我猜这是因为“mainWindow”是在另一个文件(或名称空间?)中声明的。。我已经编辑了我的答案。
PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
<MainWindow x:Name="mainWindow">
    <UserControl Tag="{x:Reference mainWindow}">
</MainWindow>
<UserControl x:Name="userControl">
<PopUp PlacementTarget="{Binding Path=Tag, ElementName=userControl}"/>
</UserControl>