我正在尝试提取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时没有任何反应。
如果Command
位于ViewCell后面的代码中,则必须将Command Binding
的源设置为视图单元格。以下示例。
<BoxView.GestureRecognizers>
<TapGestureRecognizer Command="{Binding DetailsCommand, Source={x:Reference Cell}}" CommandParameter="{Binding .}" NumberOfTapsRequired="1"/>
</BoxView.GestureRecognizers>
然后在ViewCell上你需要设置x:Name
。必须为Binding x:Reference to work设置。
<ViewCell x:Name="Cell">
编辑
ViewModel.cs
public class ViewModel
{
public ObservableCollection<MyObject> ItemsSource { get; set; } = new ...
}
MyObject.cs - 这是你的ViewCell
的BindingContext
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
需要在你的ItemsSource
而不是你的ViewModel中用作对象的MyObject.cs类中。