Category / Section
How to perform the right-click action in the listview in Xamarin.Forms UWP platform?
ListView allows you perform the right-click action in UWP platform by customizing the ListView and ListViewItem.
Click here to know more details about customization of listview item.
xaml
<ContentPage xmlns:local="clr-namespace:ListViewContextMenu">
<local:SfListViewExt x:Name="listView" ItemsSource="{Binding ContactsInfo}">
<local:SfListViewExt.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="{Binding ContactImage}"/>
<Label Text="{Binding ContactName}"/>
<Label Text="{Binding ContactNumber}"/>
<Label Text="{Binding ContactType}"/>
</Grid>
</DataTemplate>
</local:SfListViewExt.ItemTemplate>
<local:SfPopUpView IsVisible="{Binding ShowPopUp, Mode=TwoWay}"
ListView="{x:Reference listView}"/>
</local:SfListViewExt>
</ContentPage>
C#
Extension class of SfListView and RightTappedEventArgs
public class SfListViewExt : SfListView
{
public event ItemRightTappedEventHandler ItemRightTapped;
public void RaiseItemRightTapped(ItemRightTappedEventArgs e)
{
if (ItemRightTapped != null)
this.ItemRightTapped(this, e);
}
}
public delegate void ItemRightTappedEventHandler(object sender, ItemRightTappedEventArgs e);
public class ItemRightTappedEventArgs : EventArgs
{
private object itemData = null;
private Point position;
public ItemRightTappedEventArgs(object itemData, Point position)
{
this.itemData = itemData;
this.position = position;
}
public object ItemData
{
get { return itemData; }
}
public Point Position
{
get { return position; }
}
}
Extend the ItemRenderer in the UWP renderer project, raise the right tapped event, and then pass the data and position into the pcl.
public class ListViewItemRendererExt : ListViewItemRenderer
{
public ListViewItemRendererExt()
{
this.RightTapped += ListViewItemRendererExt_RightTapped;
}
private void ListViewItemRendererExt_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e)
{
var listviewitem = this.Element as ListViewItemExt;
if (listviewitem != null)
{
var location = this.TransformToVisual(null).TransformPoint(e.GetPosition(this));
var tappedEventArgs = new ItemRightTappedEventArgs(this.Element.BindingContext, new Xamarin.Forms.Point(location.X, location.Y));
listviewitem.ListView.RaiseItemRightTapped(tappedEventArgs);
}
}
}
Show popup when right-click the mouse.
listview.ItemRightTapped += Listview_ItemRightTapped;
private void Listview_ItemRightTapped(object sender, ItemRightTappedEventArgs e)
{
item = e.ItemData as Contacts;
this.ShowPopup(e.Position.X, e.Position.Y);
}
Sample: Right click action in UWP