【问题标题】:WPF Popup placement relative to main windowWPF 弹出窗口相对于主窗口的位置
【发布时间】: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>

ma​​inWindow元素名称是我的主窗口之一,声明如下:

<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}}"。谢谢!

标签: wpf xaml popup placement


【解决方案1】:

尝试通过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=Window} 你需要修改它。

【讨论】:

  • Nope 不起作用,在运行时抛出“System.Windows.Markup.XamlParseException”(“无法解析引用”)。我猜那是因为“mainWindow”是在另一个文件(或命名空间?)中声明的。
  • 我想,MainWindow 中的 PopUp.. 我已经编辑了我的答案。
猜你喜欢
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 2011-04-27
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多