如何在XAML中将弹出窗口居中显示?

3
我希望在我的窗口(高度="400"宽度="500")上有一个居中的弹出通知。请查看下面的XAML代码。是否可以仅使用XAML将其居中(而不需要在代码后台进行操作)?
    </Grid>
    <TextBlock Text="TEXT" Grid.Row="1" Grid.Column="0" Grid.RowSpan="2" Grid.ColumnSpan="3" FontSize="200" FontWeight="Bold" HorizontalAlignment="Center"/>
    <Grid Grid.Row="1" Grid.Column="1">

        <Popup x:Name="PopupName" Grid.ColumnSpan="2" IsOpen="{Binding ElementName=ToggleButton,Path=IsChecked}" StaysOpen="False" Placement="Absolute" 
            AllowsTransparency="True"  PopupAnimation="None"   Focusable="False" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Grid Height="400" Width="500">
                <Rectangle Fill="Silver" Opacity="0.5" Panel.ZIndex="1" Height="400" Width="500"/>

                <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Panel.ZIndex="2" Height="150" Width="150">
                    <ListBox Height="Auto" HorizontalAlignment="Center" >
                        <Label Content="Red" Background="Red" Margin="5" VerticalAlignment="Top"/>
                        <Label Content="Green" Background="Green" Margin="5" VerticalAlignment="Center"/>
                        <Label Content="Yellow" Background="Yellow" Margin="5" VerticalAlignment="Bottom"/>
                    </ListBox>
                </StackPanel>

                <ToggleButton Panel.ZIndex="2" Background="Coral" Foreground="White" FontWeight="Bold" Name ="Button"  Width="80" Height="30" HorizontalAlignment="Center"  Margin="5,170,5,5" Content="Close" Click="Button_OnClick"/>
            </Grid>
        </Popup>
    </Grid>

另一种选择是使用 "Placement='AbsolutePoint'" 与水平/垂直偏移量,但这似乎有点奇怪:D 有什么建议吗?谢谢;)

1
可能是重复问题:https://dev59.com/8nI-5IYBdhLWcg3wn5y5 - Barracoder
1
谢谢提供链接,但它将弹出窗口的左上角放在屏幕中央,而不是将弹出窗口居中于我的窗口。我想做到不需要代码后台。有什么想法吗? - Dôn Kayt
1个回答

4

这将使 Popup 在父窗口中居中显示:

<Popup ...
    Placement="Center" 
    PlacementTarget="{Binding RelativeSource={RelativeSource AncestorType=Window}}" />

这非常有帮助。谢谢 :) - Dôn Kayt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接