在项目的BoxView上获取ListView项目ID,点击Xamarin.Forms

问题描述 投票:0回答:1

我正在尝试提取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时没有任何反应。

c# listview xamarin.forms binding parameter-passing
1个回答
0
投票

如果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类中。

© www.soinside.com 2019 - 2024. All rights reserved.