UWP - 可在页面内移动的弹出菜单

问题描述

新年快乐。

我是 UWP 的新手,我正在尝试各种新事物。

我想做一个可以在页面内移动的弹出菜单

用户点击按钮时,会显示相应的菜单,我希望可以随时在屏幕内移动。

显示在Flyout、Popup等固定位置,不能移动。 你有什么好的想法吗?

解决方法

要移动 PopUp 控件,您需要处理放入 PopUp 的内容的 Pointer 事件。然后根据指针位置改变PopUp的位置。

我做了一个简单的演示,你可以试试:

XML 代码:

 <Grid>
    <StackPanel>
        <Button Content="Show Popup (using Offset)" Click="ShowPopupOffsetClicked"/>
    </StackPanel>
    <Popup VerticalOffset="10" HorizontalOffset="200" x:Name="StandardPopup"  >
        <Border BorderBrush="Black" 
                Background="Gray"
                PointerPressed="StandardPopup_PointerPressed"
                PointerMoved="StandardPopup_PointerMoved"
                PointerReleased="StandardPopup_PointerReleased"
                BorderThickness="2" 
                Width="200" 
                Height="200">
            <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                <TextBlock Text="Simple Popup" FontSize="24.667" HorizontalAlignment="Center"/>
            </StackPanel>
        </Border>
    </Popup>
</Grid>

背后的代码:

 public sealed partial class MainPage : Page
{
    public bool isDraging { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        isDraging = false;

    }

    private void StandardPopup_PointerPressed(object sender,PointerRoutedEventArgs e)
    {
        //enable dragging
        isDraging = true;
        e.Handled = true;
    }

    private void StandardPopup_PointerMoved(object sender,PointerRoutedEventArgs e)
    {
        if (isDraging)
        {
            //get pointer position
            var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;
            var x = pointerPosition.X - Window.Current.Bounds.X;
            var y = pointerPosition.Y - Window.Current.Bounds.Y;
            //change position
            StandardPopup.HorizontalOffset = x-100;
            StandardPopup.VerticalOffset = y-100;
        }

        e.Handled = true;
    }

    private void StandardPopup_PointerReleased(object sender,PointerRoutedEventArgs e)
    {
        //disable dragging
        isDraging = false;
        e.Handled = true;
    }

    private void ClosePopupClicked(object sender,RoutedEventArgs e)
    {
        // if the Popup is open,then close it 
        if (StandardPopup.IsOpen) { StandardPopup.IsOpen = false; }
    }

    // Handles the Click event on the Button on the page and opens the Popup. 
    private void ShowPopupOffsetClicked(object sender,RoutedEventArgs e)
    {
        // open the Popup if it isn't open already 
        if (!StandardPopup.IsOpen) { StandardPopup.IsOpen = true; }
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...