ListView ItemClick在Xamarin.Forms(iOS)中不起作用

时间:2016-08-03 13:40:08

标签: c# xaml xamarin xamarin.forms

我们有一个自定义ListView,其ItemClickCommand属性。我们使用local关键字将其绑定在XAML文件中。它适用于Xamarin.Forms Android,但它在Xamarin.forms iOS中无法点击。

请在代码中建议如何继续或我们做错了什么。

代码如下:

XAML文件:

<StackLayout x:Class="XYZ"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:XYZ.UI;assembly=XYZ">

            <local:ListView ItemClickCommand="{Binding OnDataSelectionCommand, Mode=TwoWay}" ItemsSource="{Binding DataList}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>

                            <StackLayout Orientation="Horizontal">
                                <Label FontSize="17"
                                       HorizontalOptions="Start"
                                       Text="{Binding }"
                                       TextColor="Black"
                                       VerticalOptions="Center" />


                                <Label FontSize="17"
                                       HorizontalOptions="Start"
                                       Text=" , "
                                       TextColor="Black"
                                       VerticalOptions="Center" />


                            </StackLayout>
                        </ViewCell>

                    </DataTemplate>
                </ListView.ItemTemplate>
            </local:ListView>

查看型号:

private Command _onDataSelectionCommand;
public Command OnDataSelectionCommand
{
      get
      {
           return _onDataSelectionCommand ?? (_onDataSelectionCommand = new Command(async (s) =>
           {
                // TODO: get selected item from list !!
           }));
       }
}

自定义列表已创建:

  using System.Windows.Input;
  using Xamarin.Forms;         
  namespace XYZ.UI
  {     

    public class ListView : Xamarin.Forms.ListView
   {
    public static BindableProperty ItemClickCommandProperty = BindableProperty.Create<ListView, ICommand>(x => x.ItemClickCommand, null);

    public ListView()
    {
        this.ItemTapped += this.OnItemTapped;
    }

    public ICommand ItemClickCommand
    {
        get { return (ICommand)this.GetValue(ItemClickCommandProperty); }
        set { this.SetValue(ItemClickCommandProperty, value); }
    }

    private void OnItemTapped(object sender, ItemTappedEventArgs e)
    {
        if (e.Item != null && this.ItemClickCommand != null && this.ItemClickCommand.CanExecute(e))
        {
            this.ItemClickCommand.Execute(e.Item);
        }
    }
  }

1 个答案:

答案 0 :(得分:0)

您必须使用ListView的SelectedItem属性进行绑定。这将为您提供绑定到列表的集合的对象(项)。

可以找到示例项目here

另请注意,ItemTappedItemSelected不同。

如果您对将命令绑定到ListView项目Tapped感兴趣,请查看此论坛帖子,了解相同的内容 - How to bind a Command to ListView.ItemTapped