【问题标题】:Getting ListView Item's Id on Item's BoxView click in Xamarin.Forms在 Xamarin.Forms 中单击项目的 BoxView 获取 ListView 项目的 ID
【发布时间】:2019-02-17 13:33:32
【问题描述】:

我正在尝试提取 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 时,什么也没有发生。

【问题讨论】:

  • 我认为您的命令可能配置错误。当您使用 CommandParameter 时,我认为您必须提供 DetailsCommand = new Command&lt;object&gt;(ShowDetails); 之类的类型另外,请确保您的 ViewCell 没有捕获点击,也没有将其传递给您的 BoxView

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


【解决方案1】:

如果CommandViewCell 后面的代码中,那么您必须将Command Binding 的源设置为视图单元格。下面的例子。

<BoxView.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding DetailsCommand, Source={x:Reference Cell}}" CommandParameter="{Binding .}" NumberOfTapsRequired="1"/>
</BoxView.GestureRecognizers>

然后在 ViewCell 上,您需要设置 x:Name。这必须设置为使 Binding x:Reference 起作用。

<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 类中,您可以在创建 ItemsSource 时传入 Id 值,并且不再需要 CommandParameter

总而言之,您的 DetailsCommand 需要位于 MyObject.cs 类中,该类被用作您的 ItemsSource 中的对象,而不是您的 ViewModel。

【讨论】:

  • 它在 ViewModel 中,ViewModel 在后面的代码中设置为 BindingContext。
  • 在这种情况下,DetailsCommand 需要位于与ObservableCollection&lt;MyObject&gt; 中的对象对应的自定义对象中。 ViewCellBindingContextMyObject 类。
  • 你能给我一些样品吗?我似乎无法解决
  • 我用ViewModel 和一个MyObject 类的小例子编辑了我的答案,该类应该是你的ViewCell 的BindingContext。
  • 所以在 xaml 我需要做 Command="{Binding ItemsSource}" 这是 ObservableCollection。正确的?还是应该将其绑定到 DetailsCommand?我不明白你为什么叫 observable collection ItemsSource
猜你喜欢
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 2011-10-02
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 2021-04-05
相关资源
最近更新 更多