我试图提取ListView项的ID,但是当我单击BoxView时,什么也没发生。
这是我的XAML(摘自ListView的ViewCell):
<BoxView Grid.Column="1" BackgroundColor="Transparent" HorizontalOptions="FillAndExpand">
<BoxView.GestureRecognizers>
<TapGestureRecognizer Command="{Binding DetailsCommand}" CommandParameter="{Binding .}" NumberOfTapsRequired="1"/>
</BoxView.GestureRecognizers>
</BoxView>
这是我的代码:
DetailsCommand = new Command(ShowDetails);
public async void ShowDetails(object obj)
{
var selected = obj as Tasks;
await _navigation.PushAsync(new DetailsPage(selected.Id));
}
但是当我单击BoxView时,没有任何反应。
答案 0 :(得分:0)
如果Command
位于 ViewCell 后面的代码中,则必须将Command Binding
的源设置为视图单元格。下面的示例。
<BoxView.GestureRecognizers>
<TapGestureRecognizer Command="{Binding DetailsCommand, Source={x:Reference Cell}}" CommandParameter="{Binding .}" NumberOfTapsRequired="1"/>
</BoxView.GestureRecognizers>
然后在ViewCell上需要设置x:Name
。必须对此进行设置,以使绑定x:参考起作用。
<ViewCell x:Name="Cell">
修改
ViewModel.cs
public class ViewModel
{
public ObservableCollection<MyObject> ItemsSource { get; set; } = new ...
}
MyObject.cs -这是您的ViewCell
public class MyObject
{
public int Id { get; }
public ICommand DetailsCommand { get; }
// Other properties if needed
public MyObject(int id)
{
Id = id;
DetailsCommand = new Command(ShowDetails);
}
private async void ShowDetails()
{
var selected = obj as Tasks;
await _navigation.PushAsync(new DetailsPage(Id));
}
}
在 MyObject 类中,您可以在创建Id
时传递一个ItemsSource
值,并且也不再需要CommandParameter
。
总而言之,您的DetailsCommand
必须位于 MyObject.cs 类中,该类将用作ItemsSource
中的对象,而不是ViewModel中的对象。>