ImageButton Command not executed in Xamarin Form CarouselView

syahman 1 Reputation point
2021-01-10T15:46:23.073+00:00

hi, im trying to implement CaroulselView and add command to imagebutton in template.

            <CarouselView ItemsSource="{Binding weblinks}"
              PeekAreaInsets="100" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"
                              VerticalOptions="FillAndExpand"
                              HeightRequest="210">
                    <CarouselView.ItemTemplate>
                        <DataTemplate>
                            <StackLayout>
                                <Frame HasShadow="True"
                       BorderColor="DarkMagenta"
                       CornerRadius="2"
                       Margin="5"
                       HeightRequest="200"
                       WidthRequest="200"
                       >
                                    <StackLayout>
                                        <ImageButton Source="{Binding ImageUrl}" Aspect="AspectFill"
                               HeightRequest="200"
                               WidthRequest="200"
                               HorizontalOptions="EndAndExpand" Command="{Binding TapImgCommand}"></ImageButton>

                                    </StackLayout>

                                </Frame>
                            </StackLayout>
                        </DataTemplate>
                    </CarouselView.ItemTemplate>
                </CarouselView>

in viewmodel :
public DelegateCommand TapImgCommand => new DelegateCommand(NavigateWebview);

async void NavigateWebview()
{
await SLDialog.AlertAsync("Test!!!!!");
await Browser.OpenAsync("http://www.google.com", BrowserLaunchMode.SystemPreferred);
}

TapImgCommand never executed in mvvm if use in carouselview (as template data). i tried to put imagebutton outside carouselview to test and it able to execute command.

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Ángel Rubén Valdeolmos Carmona 611 Reputation points
    2021-01-10T20:03:27.883+00:00

    In your weblinks list, you should have a command property in your object, but it doesn't because you will have it directly in the viewmodel.

    Try this:

    xmlns:viewmodels="clr-namespace:YourApp.ViewModelFolder"

    Command="{Binding Source={RelativeSource AncestorType={Type viewmodels:YourViewModel}}, Path=TapImgCommand}"

    1 person found this answer helpful.
    0 comments No comments

  2. JessieZhang-MSFT 7,716 Reputation points Microsoft External Staff
    2021-01-12T09:28:23.743+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    Another method is to add EventHandler in each item model of your weblinks.

    You can refer to the following code:

    Item code(Image.cs)

    public class Image  
        {  
            public string Name { get; set; }  
            public string Caption { get; set; }  
      
            public Command TapCommand { get; set; }  
      
            public EventHandler TapClickEventHandler;  
      
            public Image()  
            {  
                TapCommand = new Command(() => OnImageClicked());  
            }  
      
            public void OnImageClicked()  
            {  
                TapClickEventHandler?.Invoke(this, EventArgs.Empty);  
            }  
        }  
    

    ImagesViewModel.cs(The ViewModel of testpage)

      public class ImagesViewModel  
        {  
            public ObservableCollection<Image> Images { get; set; }  
      
            public ImagesViewModel()  
            {  
                Images = new ObservableCollection<Image>  
                {  
                    new Image  
                    {  
                        Name = "sanfrancisco.jpg",  
                        Caption = "San Francisco",  
                        TapClickEventHandler = OnTapped  
      
                    },  
                        new Image  
                    {  
                        Name = "alameda.jpg",  
                        Caption = "Alameda",  
                        TapClickEventHandler = OnTapped  
                    },  
                    new Image  
                    {  
                        Name = "sanleandro.jpg",  
                        Caption = "San Leandro",  
                        TapClickEventHandler = OnTapped  
                    }  
                };  
            }  
      
            int taps = 0;  
      
            void OnTapped(object sender, EventArgs e)  
            {  
                taps++;  
                var img = (Image)sender;  
                Debug.WriteLine($"tapped: {taps}  {img.Name}");  
            }  
        }  
    

    xaml code:

     <cv:CarouselViewControl ItemsSource="{Binding Images}"  
                    Orientation="Horizontal" InterPageSpacing="10" Position="1" HorizontalOptions="FillAndExpand">  
                    <cv:CarouselViewControl.ItemTemplate>  
                        <DataTemplate>  
                            <StackLayout>  
                                <StackLayout BackgroundColor="#80000000" Padding="12">  
                                    <Label TextColor="White" Text="{Binding Caption}" FontSize="16" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>  
                                </StackLayout>                            
                                <Image Aspect="AspectFill" Source="{Binding Name, Converter={StaticResource imageConverter}}">  
                                    <Image.GestureRecognizers>  
                                        <TapGestureRecognizer Command="{Binding TapCommand}" NumberOfTapsRequired="1" />  
                                    </Image.GestureRecognizers>                               
                                </Image>  
                            </StackLayout>  
                        </DataTemplate>  
                    </cv:CarouselViewControl.ItemTemplate>  
                </cv:CarouselViewControl>  
    

    For more details, you can refer to: https://github.com/mikeacosta/clickable-carouselview

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.