在 Xamarin 应用程序的 ListView 中连接项目命令

Wiring item command in a ListView in Xamarin app

我正在尝试将 ListViewCommand 连接到我的 VendorsViewModel,但一直出现以下错误。

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

这是我的 ListView 代码:

<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>

这是我的 VendorsViewModel 代码:

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   
   }
}

我做错了什么?

主要问题在此参考中。参考应该是页面而不是列表。给 ContantPage 一个 x:Name 然后在 textCell

中引用它
<TextCell Text="{Binding FullName}" Command="{Binding BindingContext.VendorSelectedCommand, Source={x:Reference PageName}}"  CommandParameter="{Binding .}" />

另外尝试将您的 AsyncCommand 更改为 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
}

<ViewCell></ViewCell> 标记添加到您的 ListView。

格式如下:

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