Access list data from tapgesture from image inside viewcell

Eric888Eric888 USMember ✭✭

I have a image inside a ViewCell, I've added a TapGestureRecognizer to the image, now when the user clicks the image I want to Access the data from data ViewCell

How can I do that?

Thanks

Best Answer

Answers

  • SHUBHAMSHARMA_2927SHUBHAMSHARMA_2927 USMember ✭✭✭
    edited July 2018

    @Eric888

    You can create custom ViewCell and use it as you wish. your first page should be like this
    <ListVIew><ListView.ItemTemplate><DataTemplate><local:MyViewCell/></DataTemplate></ListView.ItemTemplate></ListView>

    and your MyViewCell Class Should be Inherit ViewCell in both cs and Xaml Page.In your CustomViewCell you have full Controll in all Controls.

  • JGoldbergerJGoldberger USMember, Forum Administrator, Xamarin Team, University Xamurai
    edited August 2018

    @Eric888

    EDIT: See better solution next post. But leaving this post as is as some might like the idea of having a view model for the view cell.

    I think easiest is to have a view model for your ViewCell and then use Command instead of Tapped to handle the image click. With Command you can pass a parameter.

    XAML:

    <TapGestureRecognizer 
                Command="{Binding ImageTapCommand}"
                CommandParameter="{Binding .}"/>
    

    Binding . passes the current item in the list, the ViewCell's view model, whose image was tapped.

    In the ViewCellViewModel:

    public ICommand ImageTapCommand { get; private set; }
    
    public ViewCellViewModel()
        {
            ImageTapCommand = new Command(ImageTapped);
        }
    
    void ImageTapped(object obj)
        {
            var item = obj as ViewCellViewModel;
            // obj is this ViewCellViewModel instance
            // so in reality you do not even need to use the obj variable
            // as you can just access the properties of the ViewCellViewModel
            // directly.
        }
    

    I've attached a sample with this in action, modified from this sample.

  • Eric888Eric888 USMember ✭✭

    Thanks for the help, tomorow i will try your solution.

Sign In or Register to comment.