2016-08-03 64 views
1

我們有一個自定義ListView它有一個ItemClickCommand屬性。我們使用local關鍵字將它綁定在XAML文件中。它適用於Xamarin.Forms Android,但在Xamarin.forms iOS中不可點擊。ListView ItemClick不能在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); 
     } 
    } 
    } 

回答

0

你必須使用ListView的SelectedItem屬性來綁定。這將爲您提供您綁定到列表的集合的對象(項目)。

示例項目可以找到here。請注意0​​與ItemSelected不同。

如果你有興趣將一個命令綁定到ListView項目點擊,那麼請看看這個論壇帖子關於相同 - How to bind a Command to ListView.ItemTapped

+0

感謝您的答覆,對於IOS點擊正在工作,但長時間按 –

+0

長按列表項? –

+0

是的,我們有一個列表視圖,上面的代碼工作正常,我們可以從ListView中選擇項目。但在iOS的情況下,我們需要長時間按下該項目才能啓動事件。 –