如何使用Xamarin Prism EventToCommand行为提取ListView项

0 listview prism xamarin

我使用棱镜图书馆与Xamarin形式,并试图使用说明的EventToCommandBehavior 这里附上一个ListView中ItemTapped行为.

执行ItemTappedCommand委托时,事件参数为null,这意味着我无法提取ListView项.

下面是我的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; } }
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

Dan*_* S. 5

正如布莱恩所说的那样,你走错了路.例如,假设我有一个字符串集合只是为了简化它,但它可以是任何东西的集合.

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);
}
Run Code Online (Sandbox Code Playgroud)

我的ListView只需要执行以下操作:

<ListView ItemsSource="{Binding People}">
    <ListView.Behaviors>
        <b:EventToCommandBehavior Command="{Binding ItemTappedCommand}" 
                                  EventName="ItemTapped"
                                  EventArgsParameterPath="Item" />
    </ListView.Behaviors>
</ListView>
Run Code Online (Sandbox Code Playgroud)

在您的视图模型的命令应该期待的对象中,你绑定到集合的确切类型ItemsSourceListView.要正确使用它,您只需EventArgs在此情况下指定路径即可Item.