在RightTapped事件下选择ListBoxItem

时间:2016-12-28 12:24:21

标签: c# uwp

我现在有以下活动

private void contactGrid_RightTapped(object sender, RightTappedRoutedEventArgs e)
{         

    if (contactGrid.SelectedIndex >= 0)
    {    
        FrameworkElement senderElement = sender as FrameworkElement;

        MenuFlyout menu = new MenuFlyout();
        MenuFlyoutItem item1 = new MenuFlyoutItem() { Text = "Edit Contact" };
        MenuFlyoutItem item2 = new MenuFlyoutItem() { Text = "Comfirm" };
        MenuFlyoutSubItem item2a = new MenuFlyoutSubItem() { Text = "Remove Contact" };

        item1.Click += new RoutedEventHandler(EditContactClicked);
        item2.Click += new RoutedEventHandler(RemoveContactClicked);

        item2a.Items.Add(item2);


        menu.Items.Add(item1);
        menu.Items.Add(item2a);

        menu.ShowAt(senderElement, e.GetPosition(contactGrid));
    }
}

这样可以正常工作,并在列表框项目顶部的鼠标指针处创建右键单击上下文菜单,但前提是它已被选中。我无法弄清楚的是如何让RightTapped事件选择正确点击的项目。我还没有在平板电脑模式下测试它 我正在使用鼠标来触发正确的点击事件(通过右键单击)。

是否在平板电脑模式下长按(触发右键)的默认行为,以便它仍然选择项目?

1 个答案:

答案 0 :(得分:1)

据我了解,contactGrid是您的ListBox?我猜你有任何ListCollection设置为ListBox的ItemsSource?然后,您可以在右侧的tapped-event中设置SelectedItem属性,如下所示:

首先,您需要修改ItemTemplate,以便RightTapped属于ListBoxItem:

<ListBox x:Name="ContactGrid">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border Background="Transparent" RightTapped="contactGridItem_RightTapped">
                <TextBlock Text="{Binding}" />
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

在代码中(我实际上想知道Flyout显示在selectedItem上方而不是整个ListBox上方):

private void contactGridItem_RightTapped(object sender, RightTappedRoutedEventArgs e)
{         
    FrameworkElement senderElement = sender as FrameworkElement;

    // Now you can get the tapped Item from the DataContext and set is as selected
    contactGrid.SelectedItem = senderElement.DataContext;

    if (contactGrid.SelectedIndex >= 0)
    {    

        MenuFlyout menu = new MenuFlyout();
        MenuFlyoutItem item1 = new MenuFlyoutItem() { Text = "Edit Contact" };
        MenuFlyoutItem item2 = new MenuFlyoutItem() { Text = "Comfirm" };
        MenuFlyoutSubItem item2a = new MenuFlyoutSubItem() { Text = "Remove Contact" };

        item1.Click += new RoutedEventHandler(EditContactClicked);
        item2.Click += new RoutedEventHandler(RemoveContactClicked);

        item2a.Items.Add(item2);


        menu.Items.Add(item1);
        menu.Items.Add(item2a);

        menu.ShowAt(senderElement, e.GetPosition(contactGrid));
    }
}

(未经测试,但这就是我将如何解决它)