gpt4 book ai didi

xamarin - 单击 "Cell control"like 按钮时获取 ListView 项目

转载 作者:行者123 更新时间:2023-12-03 10:56:32 28 4
gpt4 key购买 nike

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

这是 ListView

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

列表截图:

enter image description here

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

错误截图:

enter image description here

最佳答案

您可以使用命令绑定(bind)来执行此操作:

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

关于xamarin - 单击 "Cell control"like 按钮时获取 ListView 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56188913/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com