Home > Software engineering >  Wiring item command in a ListView in Xamarin app
Wiring item command in a ListView in Xamarin app

Time:03-04

I'm trying to wire a ListView item Command to my VendorsViewModel but keep getting the following error.

VendorSelectedCommand property not found on MyProject, target property Xamarin.Forms.TextCell.Command

Here's my ListView code:

<ListView
   x:Name="VendorsList"
   ItemsSource="{Binding Vendors}"
   BackgroundColor="Transparent">
       <ListView.ItemTemplate>
           <DataTemplate>
               <TextCell Text="{Binding FullName}" Command="{Binding Source={x:Reference Name=VendorsList}, Path=BindingContext.VendorSelectedCommand}" CommandParameter="{Binding .}" />
           </DataTemplate>
       </ListView.ItemTemplate>
</ListView>

And here's my VendorsViewModel code:

public class VendorsViewModel : BaseViewModel
{
   public LayoutState _mainState;
   public AsyncCommand VendorSelectedCommand;
   public VendorsViewModel()
   {
       Title = string.Empty;
       IsBusy = true;
       MainState = LayoutState.Loading;
       VendorSelectedCommand = new AsyncCommand(VendorSelected);
   }

   public LayoutState MainState
   {
       get => _mainState;
       set => SetProperty(ref _mainState, value);
   }

   ObservableRangeCollection<Vendor> vendors = new ObservableRangeCollection<Vendor>();
   public ObservableRangeCollection<Vendor> Vendors
   {
       get => vendors;
       set
       {
           if (vendors == value)
               return;

           vendors = value;
           OnPropertyChanged(nameof(Vendors));
       }
   }

   async Task VendorSelected(Vendor vendor)
   {
       var route = $"{nameof(VendorProfile)}";
       await Shell.Current.GoToAsync(route);
   }

   public async void Init()
   {
       IsBusy = true;
       MainState = LayoutState.Loading;
       // Call my service method to populate vendors   
   }
}

What am I doing wrong here?

CodePudding user response:

The main issue is in this reference .The reference should be the page not the list. Give a x:Name to the ContantPage and then reference it in the textCell

<TextCell Text="{Binding FullName}" Command="{Binding Source={x:Reference Name=PageName}, Path=BindingContext.VendorSelectedCommand}" CommandParameter="{Binding .}" />

Plus try Changing your AsyncCommand to ICommand .

public ICommand VendorSelectedCommand {get; set;}

(VendorSelectedCommand = new Command<object>(async (o) => await VendorSelected(o)));

async Task VendorSelected(object o)
{
    // do stuff with received object
}

CodePudding user response:

Add a <ViewCell></ViewCell> tag to your ListView.

Format like this:

<ListView  x:Name="listView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
  • Related