[英]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
吗? 我猜您有任何类型的List
或Collection
设置为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.