NOTE: This is for Xamarin forms. The question which was believed to be a duplicate is actual dealing with a C# ListView
I have a List View (cross platform using Visual Studio 2017 for Mac Xamarin Forms) I have a rough understanding of data binding so I got the form to load data from a web service. Now I want to perform a few actions for each displayed row so I embedded a button in the ListView for each item. I cannot get how to add an action so that it performs some function for that row that was selected.
In the ListView I create the button this way:
<Button x:Name="prayUpButton" Command="{Binding _handle_prayupbutton_action}" Text="PU" Grid.Row="4" Grid.Column="0" />
in the code behind I have the following methods:
void handle_prayupbutton_action()
{
}
public Command _handle_prayupbutton_action
{
get { return new Command(() => handle_prayupbutton_action());
}
From my understanding you create a Command
that will then trigger the action. What am I missing here? If I put a breakpoint on void handle_prayupbutton_action()
it never hits it.
What is the best practice/correct way to add an action to a Xamarin Forms Cross Platform List View?
UPDATE 1: I changed the code below to this:
This is my header:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="prayupapp.Pages.PrayersPage" x:Name="PrayersPagePage">
So I changed the button command:
<Button x:Name="prayUpButton" Command="{Binding Source={x:Static local.PrayersPagePage._handle_prayupbutton_action}}" Text="Pray Up" Grid.Row="4" Grid.Column="0" />
I also made the command routine a Static as Julipan suggested. I am actually regressing because the list view stopped loading from the previous page now. I find that if I return the button Command to its original code (which s evidently wrong) it does work. Something is wrong with the way I am doing the binding.
ListView
is a Xamarin.Forms specific control. If you look closely, you will see the solution is the same. Note that each item in yourListView
isn't bound to the viewmodel or code-behind but refers to the instance that is shown in theListView
Cell
. That is why yourCommand
isn't fired. It is looking in the class that is represented in theCell
. Please have another look, or explain how it is different. – Gerald Versluis