Xamarin Forms ListView item Command not binding to ICommand in VM

66 views Asked by At

I have a ContentPage that has a ListView. Within the DataTemplate of the ListView is a TextCell that holds a string value that I have binded in the corresponding ViewModel. I have the command for said TextCell binded to an ICommand in my ViewModel. When I load up an emulator, and -click- a cell item, nothing happens. I don't hit my breakpoint I have in my ViewModel on the binded ICommand. Is there something I am missing? Disclaimer: I had stepped away from Xamarin for a while.

View:

<ListView ItemsSource="{Binding matchupList}" >
    
    <ListView.ItemTemplate>
        <DataTemplate>
         <TextCell Text="{Binding matchup}" Detail="{Binding matchupDescription}"  Command="{Binding SelectedCommand}" /> 
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Code-behind:

public partial class GamesByDate : ContentPage
{   
    public GamesByDate ()
    {
        InitializeComponent ();
        BindingContext = new GamesByDateViewModel(Navigation);
    }
}

ViewModel:

public ICommand SelectedCommand => new Command(async () => await GotoPage2());
public async Task GotoPage2()
    {
        try
        {
           //DoSomething

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

    }

Once again, my mission is to tap an item in the ListView, trigger ICommand, calls another method in VM. Thanks!

1

There are 1 answers

0
Liqun Shen-MSFT On

As Jason said, you could use Relative bindings. Try the following code:

<DataTemplate>
 <TextCell Text="{Binding matchup}" Detail="{Binding matchupDescription}"  Command="{Binding Source={RelativeSource AncestorType={x:Type local:MainPageViewModel}}, Path=SelectedCommand}" /> 
</DataTemplate>

Hope it works.