Skip to content Skip to sidebar Skip to footer

Mvxrecyclerview Fluent Api Binding

I am unable to bind ItemClick from MvxRecyclerView (or its Adapter) to a command on my ViewModel using Fluent API. It works if I put both ItemsSource and ItemClick in the XML so I

Solution 1:

When creating a custom MvxRecyclerViewHolder you need to make sure that you assign the Click command over to the ViewHolder. This is done in the OnCreateViewHolder override of your custom adapter.


Example for custom ViewHolder

publicclassMyAdapter : MvxRecyclerAdapter
{
    publicMyAdapter(IMvxAndroidBindingContext bindingContext)
        : base(bindingContext)
    {
    }

    publicoverride RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
    {
        var itemBindingContext = new MvxAndroidBindingContext(parent.Context, this.BindingContext.LayoutInflaterHolder);
        var view = this.InflateViewForHolder(parent, viewType, itemBindingContext);

        returnnew MyViewHolder(view, itemBindingContext)
        {
            Click = ItemClick,
            LongClick = ItemLongClick
        };
    }
}

Solution 2:

I can't reproduce your issue. I just created a new project, added a RecyclerView and added the following binding:

varset = this.CreateBindingSet<FirstView, FirstViewModel>();
set.Bind(recyclerView).For(v => v.ItemsSource).To(vm => vm.ViewModelItems);
set.Bind(recyclerView).For(v => v.ItemClick).To(vm => vm.ShowItemCommand);
set.Apply();

This works just as expected, where ItemClick triggers the ShowItemCommand. VM's look as follows:

publicclassViewModelItem : MvxViewModel
{
    publicvoidInit(string itemId)
    {
        Mvx.Trace($"Showing {itemId}");
    }

    publicstring Id { get; set; }
}


publicclassFirstViewModel
    : MvxViewModel
{
    publicFirstViewModel()
    {
        ViewModelItems = new ViewModelItem[] {
            new ViewModelItem { Id = "Hello"},
            new ViewModelItem { Id = "World"},
            new ViewModelItem { Id = "Foo"},
            new ViewModelItem { Id = "Bar"},
            new ViewModelItem { Id = "Baz"}
        };
    }

    private IEnumerable<ViewModelItem> _viewModelItems;
    public IEnumerable<ViewModelItem> ViewModelItems
    {
        get { return _viewModelItems; }
        set { SetProperty(ref _viewModelItems, value); }
    }

    public MvxCommand<ViewModelItem> ShowItemCommand =>
        new MvxCommand<ViewModelItem>(DoShowItem);

    privatevoidDoShowItem(ViewModelItem item)
    {
        ShowViewModel<ViewModelItem>(new { itemId = item.Id });
    }
}

Post a Comment for "Mvxrecyclerview Fluent Api Binding"