In this question UWP: how to get the RightTapped GridView Item , there is a way to get the "right clicked" item in GridView (in UWP, GridView is almost the same as ListView):
var student = (e.OriginalSource as FrameworkElement)?.DataContext as Student;
The ?. symbol is interesting because when you right clicked on an item using mouse, this is OK. But when you "righttapped" an item using the Menu Button (https://en.wikipedia.org/wiki/Menu_key) or using the Menu Button on Xbox Controller, this is NOT ok because the value is null (actually the type of OriginalSource is GridViewItem).
Though I have found a solution:
- use
(((GridViewItem)e.OriginalSource).Content as YOUR_ITEM_DATA_TYPE)to handle menu button - use
(e.OriginalSource as FrameworkElement)?.DataContext as YOUR_ITEM_DATA_TYPEto handle mouse right click
typeof(e.OriginalSource) can be used with if...else... to choose which solution to use.
But is this the real best solution? Microsoft designed UWP and said it is optimized to handle mouse, keyboard, gamepad such as Xbox controller and even eye tracker seamlessly. So are there a better way to handle the "context menu" (https://docs.microsoft.com/en-us/windows/uwp/design/input/gamepad-and-remote-interactions#accelerator-support) action?
My target:
left click an item → do something about itemlist[clicked index]
right click an item → open a menu such as edit, delete → click edit → do something about itemlist[right clicked index]
PS: Try "Settings" in Windows 10, it works fine to "right click" an item (to pin a tile in start menu) using mouse , keyboard or Xbox Controller