Xamarin Forms – Binding List Item Commands to the Parent ViewModel

This post shows how to bind a list item command to the parent list views binding context. Often you want to send the command to the view model, not the object that the list item is bound to.

<?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="App1.DemoPage">
   <ListView ItemsSource="{Binding Items}" x:Name="List">
      <ListView.ItemTemplate>
         <DataTemplate>
            <TextCell Text="{Binding}" Command="{Binding Path=BindingContext.ListItemCommand, Source={x:Reference Name=List}}" CommandParameter="{Binding}" />
         </DataTemplate>
      </ListView.ItemTemplate>
   </ListView>
</ContentPage>

To do it we have given the list view a name. Then in the item command binding we use that reference in the binding path. The command parameter is the list item’s binding context.

Advertisements
Xamarin Forms – Binding List Item Commands to the Parent ViewModel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s