我有一個使用一個窗口作爲主窗口的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}}"
你有沒有試過相對的來源? 'PlacementTarget =「{Binding RelativeSource = {RelativeSource AncestorType = MainWindow}}」' – ASh
「MainWindow」不起作用,因爲類型不被WPF識別。然而,使用「窗口」它的工作原理:PlacementTarget =「{Binding RelativeSource = {RelativeSource AncestorType = Window}}」。謝謝! – Cleo