Hi Folks, I'm having a problem when trying to bind a command in a ViewCell, I'm using a DataTemplateSelector, since this ViewCell will be used in some other ListViews of the same kind, this is what I have so far:
Page<ListView ItemsSource="{Binding InTheatersList}" x:Name="lsMovies" RowHeight="120" ItemTemplate="{StaticResource MovieTemplateSelector}" CachingStrategy="RecycleElement"> </ListView>
in the ViewCell:
<Button Text="+ Watchlist" Command="{Binding AddWatchListCommand, Source={x:Reference InTheatersPage}" CommandParameter="{Binding BindingContext, Source={x:Reference ListView}}" />
ViewModel
the Binding will be to a List,
so I have:
public DelegateCommand<Movie> AddWatchListCommand { get; set; }
In the constructor:
AddWatchListCommand = new DelegateCommand<Movie>(async (Movie arg) => AddToWatchList(arg));
and finally I have the method
private async Task AddToWatchList(Movie movie) { ... }
....
I have been trying some approaches found out there but no luck so far
http://stackoverflow.com/questions/41128701/binding-a-command-within-a-datatemplate-xf-prism
http://stackoverflow.com/questions/35913622/button-command-binding-not-calling-the-binded-command-in-xamarin-forms
I will appreciate it!!
thanks!!
Answers
The Source Property you have assigned wrong. It should you the reference of the List.
Something Like this:
<Button Text="+ Watchlist" Command="{Binding AddWatchListCommand, Source={x:Reference lsMovies}" CommandParameter="{Binding .}}" />
you can also try by providing x:Name to your Page and use that as a reference.
Something like this:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms" prism:ViewModelLocator.AutowireViewModel="True" x:Name="YourChoice" > <Button Text="+ Watchlist" Command="{Binding AddWatchListCommand, Source={x:Reference YourChoice}" CommandParameter="{Binding .}}" />
Thank you for your answer @Sahadev_Gupta, but your solution only works when I have the ViewCell in the same Page where I have the ListView, or at least I couldn't make it work having the ViewCell in a separated file and use it as ItemTemplate with the DataTemplateSelector,
my idea is to have a ViewCell that can be used in several pages (ListViews), the ViewCell will have a Button that should pass the SelectedItem (ListView) via Command,
any suggestion?
thanks again mate! best regards!
@MCvel For me its work fine whether its a viewcell or not...
CommandParameter="{Binding .}}"
The . returns the selected item
Any luck with this? @MCvel ?