UWP上实现长按ListView Item弹出上下文菜单

在UWP平台下,想实现ListView长按显示上下文菜单,提供一些功能操作。在网上找了一些资料发现可以通过MenuFlyout实现。

在UWP中MenuFlyout是最常用的上下文菜单。不仅可以在ListView上使用,还可以使用在Button、状态栏等好多地方,以后慢慢学习了解。

回到我们要实现的功能上,首先创建一个简单的ListView界面。

Xaml Code:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="listView" ItemsSource="{x:Bind Items}" IsRightTapEnabled="True">

    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:TemplateData">
            <TextBlock Text="{x:Bind Name}"/>
        </DataTemplate>
    </ListView.ItemTemplate>

    <ListView.Resources>
        <MenuFlyout x:Name="menuFlyout">
            <MenuFlyout.Items>
                <MenuFlyoutItem Name="deleteOption" Text="Delete"
Click="Select_DeleteOption"/>
                <MenuFlyoutItem Name="flagOption" Text="Flag"/>
            </MenuFlyout.Items>
        </MenuFlyout>
     </ListView.Resources>
</ListView>

</Grid>

绑定好DataTemplate。MeunFlyout添加在ListView的Resources中,也可以添加在Page的Resources中。

CS Code:


public ListViewPage()
{
    this.InitializeComponent();

    Items = new ObservableCollection();
    for (int i = 0; i < 30; i++)
    {
        Items.Add(new TemplateData { Name = "Item " + (i + 1) });
    }

    //listView.Holding += ListView_Holding;
    listView.RightTapped += ListView_RightTapped;
}

private void ListView_Holding(object sender, HoldingRoutedEventArgs e)
{
    var view = (ListView)sender;
    _selectData = ((FrameworkElement)e.OriginalSource).DataContext as TemplateData;

    var viewPoint = e.GetPosition(view);

    menuFlyout.ShowAt(view, viewPoint);
}

private void ListView_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
    var view = (ListView)sender;
    _selectData = ((FrameworkElement)e.OriginalSource).DataContext as TemplateData;
 
    var viewPoint = e.GetPosition(view);

    menuFlyout.ShowAt(view, viewPoint);
}

private void Select_DeleteOption(object sender, RoutedEventArgs e)
{
    if (_selectData != null)
    {
        Items.Remove(_selectData);
        _selectData = null;
    }
}

//数据模板类

public class TemplateData
{
    public string Name{ get; set; }
}

经过测试在手机上可以实现长按的效果使用“Holding”事件,但该事件在PC端没有效果。后来经过尝试PC端可以使用“RightTapped”事件。

上面代码中“RightTapped”事件在手机端也会呈现为长按弹出菜单的效果。但是它与“Holding”的区别是长按松开手之后才会出现菜单,“Holding”则是长按到一定时间后菜单自动弹出。所以在手机端还是“Holding”比较合适。

下面是实现的效果图:

%e6%97%a0%e6%a0%87%e9%a2%98

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s