在Xamarin.Forms

时间:2018-09-12 20:38:45

标签: c# listview xamarin.forms binding parameter-passing

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

1 个答案:

答案 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

的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必须位于 MyObject.cs 类中,该类将用作ItemsSource中的对象,而不是ViewModel中的对象。