单击 "Cell control" 赞按钮时获取 ListView 项目

Getting ListView item when clicking "Cell control" like button

我有 ListViewButtonCell。当我单击单元格的按钮时,我想获取当前项目。

这是列表视图

<ListView x:Name="list1" ItemsSource="{Binding StudentList}">
        <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Image x:Name="Image1"  Source="other.png" />
                    <Label TextColor="{StaticResource mainColor}" 
                           Text="{Binding StudentName}" />
                    <Button x:Name="mybtn"                                
                    BindingContext="{Binding Source={x:Reference list1}, Path=BindingContext}" 
                    BackgroundColor="{DynamicResource CaribGreenPresent}"
                    Text="{Binding AttendanceTypeStatusIdGet, Converter={x:StaticResource IDToStringConverter}}">
                    </Button>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

当我点击 mybtn 我想在 ViewModel 中获取当前项目时,我该怎么做?

这是我的 ViewModel 代码

private List<Student> _studentList;
public List<Student> StudentList
{
    get { return _studentList; }
    set { SetProperty(ref _studentList, value); }
}

列表截图:

编辑 1: 在 ViewModel 中出现错误:

Argument 1: cannot convert from 'method group' to 'Action'

这是代码

//Constructor
public StudentAttendanceListPageViewModel(INavigationService _navigationService):base(_navigationService)
{
    ItemCommand=new DelegateCommand<Student>(BtnClicked);
}

public DelegateCommand<Student> ItemCommand { get; }
public void BtnClicked(object sender, EventArgs args)
{
    var btn = (Button)sender;
    var item = (Student)btn.CommandParameter;
    // now item points to the Student selected from the list
}

按钮XAML

<Button x:Name="mybtn"                                
BindingContext="{Binding Source={x:Reference list1}, Path=BindingContext}" 
Command="{Binding ItemCommand }" 
CommandParameter="{Binding Source={x:Reference mybtn}}"              
Text="{Binding AttendanceTypeStatusId, Converter={x:StaticResource IDToStringConverter}}">
</Button>

错误截图:

首先,不要更改按钮的 BindingContext

<Button Clicked="BtnClicked" CommandParameter="{Binding .}" ... />

然后在你后面的代码中

protected void BtnClicked(object sender, EventArgs args)
{
  var btn = (Button)sender;
  var item = (Student)btn.CommandParameter;
  // now item points to the Student selected from the list
}

您可以使用命令绑定来完成此操作:

<Page x:Name="ThePage"
  ...>
  <ListView>
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
          ...
          <Button Command="{Binding Source={x:Reference ThePage}, Path=BindingContext.ItemCommand}"
                  CommandParameter="{Binding .}" />
        </ViewCell>
      </DataTemplate
    </ListView.ItemTemplate>
  </ListView>
</Page>

// Now in the VM...
ItemCommand = new DelegateCommand<Student>(ButtonClicked);
private void ButtonClicked(Student student)
{
  // Do something with the clicked student...
}