2017-04-14 130 views
0

我使用Prism Library和Xamarin Forms并尝试使用EventToCommandBehavior描述here在Listview上附加ItemTapped行为。如何使用Xamarin Prism EventToCommand提取ListView项目行为

当ItemTappedCommand委托被执行时,事件参数为null,这意味着我无法提取ListView Item。

下面是我的ViewModel代码:

private DelegateCommand<ItemTappedEventArgs> _itemTappedCommand; 
    public RecipeListViewModel(INavigationService navigationService) : base(navigationService) 
    { 

     RefreshDataCommand = new Command(async() => await RefreshData()); 
     _itemTappedCommand = new DelegateCommand<ItemTappedEventArgs>(args => { 
      var b = args; // args is null 
      _navigationService.NavigateAsync(nameof(Recipe)); 
     }); 
    } 

public DelegateCommand<ItemTappedEventArgs> ItemTappedCommand { get { return _itemTappedCommand; } } 

这是我的XAML

<ListView ItemsSource="{Binding Recipes}" 
      HasUnevenRows="false" 
      IsPullToRefreshEnabled="true" 
      CachingStrategy="RecycleElement" 
      IsRefreshing="{Binding IsBusy, Mode=OneWay}" 
      RefreshCommand="{Binding RefreshDataCommand}" 
      x:Name="lvRecipes"> 
     <ListView.Behaviors> 
      <b:EventToCommandBehavior EventName="ItemTapped" Command="{Binding ItemTappedCommand}" /> 
     </ListView.Behaviors> 
     <ListView.Header>.......... 
.....</ListView> 

回答

1

控制的EventArgs没有传递到视图模型。这打破了MVVM模式。只需使用EventArgsParameterPath或EventArgsConverter即可将您需要的视图模型传递给您的ViewModel。

+0

谢谢!我现在明白它是如何工作的。你的框架是一路炸弹...... –

4

正如布莱恩表示你正在以错误的方式前进。例如,说我有一个字符串集合只是为了简化它,但它可能是任何东西的集合。

public class MainPageViewModel 
{ 
    public MainPageViewModel() 
    { 
     People = new ObservableRangeCollection<string>() 
     { 
      "Fred Smith", 
      "John Thompson", 
      "John Doe" 
     }; 

     ItemTappedCommand = new DelegateCommand<string>(OnItemTappedCommandExecuted); 
    } 

    public ObservableRangeCollection<string> People { get; set; } 

    public DelegateCommand<string> ItemTappedCommand { get; } 

    private void OnItemTappedCommandExecuted(string name) => 
     System.Diagnostics.Debug.WriteLine(name); 
} 

我的ListView将随后只需要做到以下几点:

<ListView ItemsSource="{Binding People}"> 
    <ListView.Behaviors> 
     <b:EventToCommandBehavior Command="{Binding ItemTappedCommand}" 
            EventName="ItemTapped" 
            EventArgsParameterPath="Item" /> 
    </ListView.Behaviors> 
</ListView> 

在你的视图模型的命令应该是期待,你结合的ItemsSource在集合对象的确切类型ListView。要正确使用它,您只需指定EventArgs中的路径,在这种情况下,该路径仅为Item

相关问题