简体   繁体   中英

How to implement a context menu for each item in a listView

I am coding a universal windows 8.1 application and I have very limited experience with context menus I have a ListView with items that are added to it as the user adds entries. I want each item in the ListView to have the same context menu so I made a flyoutMenu resource

<Page.Resources>
    <MenuFlyout x:Name="flymenDelete">
        <MenuFlyoutItem Text="Delete"    Click="MenuFlyoutItem_Click"/>
    </MenuFlyout>
</Page.Resources>

Then I add the menu to my listView

<ListView x:Name="lstvwHours" FlyoutBase.AttachedFlyout="{StaticResource flymenDelete}" HorizontalAlignment="Left" Height="264" Margin="427,77,0,0"  VerticalAlignment="Top" Width="357" RightTapped="lstvwHours_RightTapped">
</ListView>

and I have my event to handle the right click

private void Button_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
     FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
}

The problem with this is it shows the a context menu but only for the actual ListView control and not the items inside the ListView . How do I have it so this context menu only appears when the ListViewItems are rightclicked keeping in mind that these items are not hardcoded and are added with the below code.

private void DisplayHours()
{
    for (int i = 0; i < HList.Count(); i++)
    {
        lstvwHours.Items.Add(this.HList[i].display());
    }
}

You can add a flyout to list item by the utilizing ItemTemplate property of ListView.

Just define DataTemplate for an item and it will be applied to the each list item:

<ListView x:Name="lstvwHours">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" FlyoutBase.AttachedFlyout="{StaticResource flymenDelete}" RightTapped="lstvwHours_RightTapped" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM