如何让 Popup 出现在特定的角落

How to make a Popup appear in a specific corner

我希望我的 Popup 始终出现在特定的角落(例如右下角),无论我的 View 的大小和分辨率如何。

我尝试使用 HorizontalAlignmentVerticalAlignment,但它并没有真正起作用。

这是我的代码:

<Grid x:Name="Output" HorizontalAlignment="Right" VerticalAlignment="Bottom" Grid.Row="1">
    <Popup x:Name="StandardPopup">
        <Border BorderBrush="{StaticResource ApplicationForegroundThemeBrush}" 
            Background="{StaticResource ApplicationPageBackgroundThemeBrush}"
            BorderThickness="2" Width="500" Height="500">
            <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                <WebView x:Name="WebView1" Source="https://www.bing.com/" Width="490" Height="490" HorizontalAlignment="Center"/>
            </StackPanel>
        </Border>
    </Popup>
</Grid>

遗憾的是 Popup 不支持对齐,您必须使用 偏移值

注意:不要忘记您可以使用偏移量绑定,从而通过一些 Converter 魔法获得您想要的行为。

<Popup HorizontalOffset="20" 
       VerticalOffset="10">
    <!--Content-->
</Popup>

您可以创建一个 UserControl 来帮助您实现这一点。

创建一个名为 TestPopup 的新用户控件

<UserControl
    ...
    >

    <Grid>
        <Grid HorizontalAlignment="Right" VerticalAlignment="Bottom">
            <Border BorderBrush="{StaticResource ApplicationForegroundThemeBrush}" 
            Background="{StaticResource ApplicationPageBackgroundThemeBrush}"
            BorderThickness="2" Width="500" Height="500">
                <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                    <WebView x:Name="WebView1" Source="https://www.bing.com/" Width="490" Height="490" HorizontalAlignment="Center"/>
                </StackPanel>
            </Border>
        </Grid>
    </Grid>

</UserControl>

隐藏代码:

public sealed partial class TestPopup : UserControl
{
    private Popup _popup = null;
    public TestPopup()
    {
        this.InitializeComponent();
        // If you need to top placement, please comment out the Width/Height statement below
        this.Width = Window.Current.Bounds.Width;
        this.Height = Window.Current.Bounds.Height;

        //Assign the current control to the Child property of the popup. The Child property is what the popup needs to display.
        _popup = new Popup();
        _popup.Child = this;
    }
    public void ShowPopup()
    {
        _popup.IsOpen = true;
    }
    public void HidePopup()
    {
        _popup.IsOpen = false;
    }
}

在需要的地方使用 C# 代码参考

public sealed partial class MainPage : Page
{
    private TestPopup _popup = new TestPopup();
    public MainPage()
    {
        this.InitializeComponent();
        _popup.ShowPopup();
    }
}

要保证任意宽度都在右下角,可以监听页面的SizeChanged事件

private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
{
    _popup.Width = Window.Current.Bounds.Width;
    _popup.Height = Window.Current.Bounds.Height;
    // If you need to use the Width/Height of the page
    // _popup.Width = e.NewSize.Width;
    // _popup.Height = e.NewSize.Height;
}

此致。