我在ListView
中有Button
和Cell
。当我单击单元格的按钮时,我要获取当前项目。
这是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); }
}
列出屏幕截图:
修改1: 在ViewModel中出现错误:
参数1:无法从“方法组”转换为“操作”
这是代码
//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>
错误截图:
答案 0 :(得分:2)
您可以通过命令绑定来做到这一点:
<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...
}
答案 1 :(得分:1)
首先,请勿更改按钮的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
}