У меня есть 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>
Скриншот ошибки:
Всего 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...
}
во-первых, не меняйте 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
}