【发布时间】:2017-09-06 23:42:09
【问题描述】:
我有一个 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>
mainWindow元素名称是我的主窗口之一,声明如下:
<Window x:Class="X.MainWindow" x:Name="mainWindow" ...>
问题是弹窗不是放在中间,而是放在左边。所以我的猜测是弹出窗口无法正确解析 elementName(因为它是 mainWindow 的子项的子项)。有谁知道我如何在 XAML 中解决这个问题?
更新:解决方案是使用
PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
【问题讨论】:
-
你试过相对来源吗?
PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}}" -
"MainWindow" 不起作用,因为 WPF 无法识别该类型。但是,使用“Window”它可以工作:PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType=Window}}"。谢谢!