Wiring up a Button Click handler in a Xamarin.Forms ListView

Posted: April 22, 2018 in Development, Programming, Software Development, Xamarin
Tags: , , , , , ,

So I had to deal with this recently. There were many examples out there, many of which didn’t work. Sooo, I’m blogging my code example so others don’t remain stuck 🙂

In short:

  1. In the XAML, add a CommandParameter binding, and wire up the Clicked event handler.
  2. In the C# Event Handler: Read the (sender as Button).CommandParameter and it’ll be the bound object. Cast / parse accordingly.

XAML (condensed):

<ListView x:Name=”LocationsListView”
ItemsSource=”{Binding Items}”
VerticalOptions=”FillAndExpand”
HasUnevenRows=”true”
RefreshCommand=”{Binding LoadLocationsCommand}”
IsPullToRefreshEnabled=”true”
IsRefreshing=”{Binding IsBusy, Mode=OneWay}”
Refreshing=”LocationsListView_OnRefreshing”
CachingStrategy=”RecycleElement”>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation=”Horizontal” Padding=”5″>
<StackLayout WidthRequest=”64″>
<Button
CommandParameter=”{Binding Id}”
BackgroundColor=”#4CAF50″
Clicked=”MapButtonClicked”
Text=”Map”
HorizontalOptions=”FillAndExpand”></Button>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

C#:

protected void MapButtonClicked(object sender, EventArgs e)
{
var selectedLocation = _viewModel.Items.First(item =>
item.Id == int.Parse((sender as Button).CommandParameter.ToString()));

Utility.LaunchMapApp(selectedLocation.Latitude, selectedLocation.Longitude);
}

Leave a comment