按下按钮时如何从集合视图中获取相应的对象?

How to get the corresponding object from collection view when a button is pressed?

我有一个 CollectionView,每个项目包含 2 个按钮。编辑和删除。我想在按下按钮时删除或编辑该项目。但问题是当按下内部按钮时,我如何才能获得该特定项目的相应对象?因为 selection 模式设置为 none,按下按钮也不会 select 项目。所以我无法通过以下方式访问该项目 - (Model)collView.SelectedItem.Constructor.... (//Do something where x:Name = collView).

这是我试过的东西 -

<CollectionView x:Name="RequestCollectionView"
                SelectionMode="None"
                Margin="0,35,0,0">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="users:Student">
            <StackLayout>
                    <Label x:Name="studentName"
                           Text="{Binding Name}"
                           Margin="0,25,0,0"/>
                    <Button x:Name="acceptBtn"
                            Clicked="AcceptBtn_Clicked"
                            HeightRequest="24" 
                            WidthRequest="24"/>
                    <Button x:Name="rejectBtn"
                            Clicked="RejectBtn_Clicked"
                            HeightRequest="24" 
                            WidthRequest="24" 
                            Margin="0,0,15,0"/>
            </StackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

我尝试了以下方法,但没有用 ->

private void AcceptBtn_Clicked(object sender, EventArgs e)
{
    // Here I get NullRef Exception
    testText.Text =
        ((Student)RequestCollectionView.SelectedItem).Name;
   // var t = (Student)sender; //Invalid Cast
}

If the title is not appropiate, suggest or edit please. I couldn't find the appropiate title for this question. Pardon me.

使用BindingContext

private void AcceptBtn_Clicked(object sender, EventArgs e)
{
    var btn = (Button) sender;
    var student = (Student)btn.BindingContext;

    testText.Text = student.Name;

}

将 CommandParameter 添加到您的按钮

<Button x:Name="acceptBtn"
        Clicked="AcceptBtn_Clicked"
        HeightRequest="24" 
        WidthRequest="24"
        CommandParameter="{Binding .}"/>
<Button x:Name="rejectBtn"
        Clicked="RejectBtn_Clicked"
        HeightRequest="24" 
        WidthRequest="24" 
        Margin="0,0,15,0"
        CommandParameter="{Binding .}"/>

事件处理

private void AcceptBtn_Clicked(object sender, EventArgs e)
{
    if(sender is Button b && b.CommandParameter is Student student)
    {
       testText.Text = student.Name;
    }
}