2017-04-11 315 views
1

我有一個使用一個窗口作爲主窗口的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}}" 
+1

你有沒有試過相對的來源? 'PlacementTarget =「{Binding RelativeSource = {RelativeSource AncestorType = MainWindow}}」' – ASh

+0

「MainWindow」不起作用,因爲類型不被WPF識別。然而,使用「窗口」它的工作原理:PlacementTarget =「{Binding RelativeSource = {RelativeSource AncestorType = Window}}」。謝謝! – Cleo

回答

2

試圖通過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 =窗口}你將需要修改它。

+0

Nope不起作用,在運行時拋出'System.Windows.Markup.XamlParseException'(「Reference無法解析」)。我想這是因爲「mainWindow」是在另一個文件(或命名空間?)中聲明的。 – Cleo

+0

我曾想過,MainWindow中的PopUp ..我編輯了我的答案。 – Rekshino