WPF相对于主窗口的弹出窗口位置
问题描述:
我有一个使用一个窗口作为主窗口的WPF应用程序。现在我想要在窗口中显示各种弹出窗口。当弹出窗口放置在窗口内时,这可以正常工作。但是,我已经实现了弹出窗口作为用户控件;这意味着主窗口包含一个用户控件,它本身包含实际的弹出窗口。所以UI元素树是这个样子:WPF相对于主窗口的弹出窗口位置
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>
的主窗口元素名称是我的主要窗口,这是一个宣布如下:
<Window x:Class="X.MainWindow" x:Name="mainWindow" ...>
问题是弹出不放在中心,但在左侧。所以我的猜测是弹出窗口无法正确解析elementName(因为它是mainWindow子窗口的子窗口)。有谁知道我可以如何解决这个问题在XAML?
更新:的解决方案是使用
PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
答
试图通过x:Reference
到进入您的主窗口。这一个应该工作:
<MainWindow x:Name="mainWindow">
<UserControl Tag="{x:Reference mainWindow}">
</MainWindow>
<UserControl x:Name="userControl">
<PopUp PlacementTarget="{Binding Path=Tag, ElementName=userControl}"/>
</UserControl>
这样的方式,你可以在另一个控制/用户控件使用您的用户控件,你会不会需要对其进行修改,只需设置Tag属性从外面,如果你使用{的RelativeSource AncestorType =窗口}你将需要修改它。
你有没有试过相对的来源? 'PlacementTarget =“{Binding RelativeSource = {RelativeSource AncestorType = MainWindow}}”' – ASh
“MainWindow”不起作用,因为类型不被WPF识别。然而,使用“窗口”它的工作原理:PlacementTarget =“{Binding RelativeSource = {RelativeSource AncestorType = Window}}”。谢谢! – Cleo