簡體   English   中英

在RightTapped事件下選擇ListBoxItem

[英]Select ListBoxItem under RightTapped event

我現在有以下活動

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事件以選擇被正確點擊的項目。 我尚未在平板電腦模式下對此進行測試,並且我目前正在使用鼠標觸發正確的點擊事件(通過右鍵單擊)。

在平板電腦模式下長按(觸發右擊)的默認行為是否仍然可以選擇項目?

據我了解, contactGrid是您的ListBox嗎? 我猜您有任何類型的ListCollection設置為ListBox的ItemsSource嗎? 然后,您可以在右側的點擊事件中設置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));
    }
}

(未經測試,但這就是我要解決的方法)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM