0
votes

I'm using a carouselview to display a series of images. When I load one I should go to another activity.

What is happening is that inside the carrouselview it does not detect tapgesture.

I read the documentation and says to use the command instead of tapped. But I'm doing something wrong so he doesn't detect the command.

My xaml page(Report):

  <!--Cartão das fotos-->
            <Frame x:Name="cartaoFerida" HorizontalOptions="FillAndExpand"  BackgroundColor="{StaticResource ferida}" Margin="8,16,8,0"  Padding="6">
                <Frame.HasShadow>
                    <OnPlatform x:TypeArguments="x:Boolean" >
                        <On Platform="Android" Value="true"/>
                        <On Platform="iOS" Value="false"/>
                    </OnPlatform>
                </Frame.HasShadow>


                <StackLayout Orientation="Vertical" HorizontalOptions="Fill">
                    <StackLayout Orientation="Horizontal">

                        <StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal" >
                            <Label x:Name="CartaoTituloReport" Margin="20,18,0,0" TextColor="{StaticResource white}" FontSize="16" FontAttributes="Bold">


                            </Label>
                        </StackLayout>

                        <StackLayout HorizontalOptions="End" Orientation="Horizontal" Margin="0,0,-24,0" >

                            <Frame  BackgroundColor="{StaticResource white}" HeightRequest="20"  WidthRequest="100" CornerRadius="12" Margin="8,20,8,8"  Padding="2" HasShadow="False">
                                <Label x:Name="LabelEstadoFerida"  Margin="8,0,0,0" Text="{translator:Translate Aberto}" TextColor="{StaticResource ferida}" VerticalOptions="Center" FontSize="12" FontAttributes="Bold"  />
                            </Frame>

                        </StackLayout>
                    </StackLayout>

                    <RelativeLayout HorizontalOptions="Center" HeightRequest="220" WidthRequest="330">

                        <controls:CarouselViewControl x:Name="Carrousel"  Orientation="Horizontal" HorizontalOptions="Center" ItemsSource="{Binding Interventions}"  HeightRequest="220" WidthRequest="330" Margin="0,16,0,0" ShowIndicators="True" IndicatorsTintColor="{StaticResource Unselected}"  CurrentPageIndicatorTintColor="{StaticResource white}" >
                            <controls:CarouselViewControl.GestureRecognizers>
                                <TapGestureRecognizer Command="{Binding Path=BindingContext.ViewItemsDetailsCommand, Source={x:Reference Name=Carrousel}}"
                                          CommandParameter="{Binding}"/>
                            </controls:CarouselViewControl.GestureRecognizers>


                            <controls:CarouselViewControl.ItemTemplate>

                                <DataTemplate>
                                    <StackLayout Orientation="Vertical" >


                                        <Label Text="{Binding woundPhoto[0].createdAt}" TextColor="{StaticResource white}" FontAttributes="Bold" FontSize="12" HorizontalOptions="Center"/>

                                        <RelativeLayout WidthRequest="220" HeightRequest="165" VerticalOptions="Center" HorizontalOptions="Center" >


                                            <Image x:Name="Imagem" Source="{Binding woundPhoto[0].photoUri }" Aspect="AspectFill" WidthRequest="220" HeightRequest="165">
                                                <Image.GestureRecognizers>
                                                    <TapGestureRecognizer Command="{Binding Source={x:Reference Carrousel}, Path=BindingContext.Command_ImageTapped}"/>
                                                </Image.GestureRecognizers>
                                            </Image>

                                            <StackLayout WidthRequest="220" HeightRequest="165" Orientation="Horizontal" >
                                                <Image x:Name="CameraImage" WidthRequest="22" HeightRequest="22" HorizontalOptions="EndAndExpand" VerticalOptions="StartAndExpand" Margin="0,8,0,0">
                                                    <Image.Source>
                                                        <OnPlatform x:TypeArguments="ImageSource">
                                                            <On Platform="Android" Value="ic_camera.xml"/>
                                                            <On Platform="iOS" Value="ic_camera.png"/>
                                                        </OnPlatform>
                                                    </Image.Source>

                                                </Image>
                                                <Label x:Name="Index" Text="{Binding woundPhoto.Count}" TextColor="{StaticResource white}" FontSize="14" FontFamily="{StaticResource RegularFontFamily} " VerticalOptions="StartAndExpand" HorizontalOptions="End" Margin="0,8,8,0"/>
                                            </StackLayout>
                                        </RelativeLayout>

                                    </StackLayout>

                                </DataTemplate>

                            </controls:CarouselViewControl.ItemTemplate>

                        </controls:CarouselViewControl>
                    </RelativeLayout>

                </StackLayout>
            </Frame>

My Viewmodel:

public class CarrouselView : INotifyPropertyChanged
{
    #region Property

    public event PropertyChangedEventHandler PropertyChanged;
    public DelegateCommand ViewItemsDetailsCommand => new DelegateCommand(On_ImageTapped);

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(storage, value))
        {
            return false;
        }

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    private void On_ImageTapped()
    {
        Console.WriteLine("ouuuuuuuuuuuuuuuuuuuuuuuuuuuu");
    }

    #endregion

    public ObservableCollection<Classes.Intervention> Interventions { get; }


    public CarrouselView(List<Classes.Intervention> intervention)
    {

        for(int i =0; i < intervention.Count; i++)
        {
            for(int j = 0; j< intervention[i].woundPhoto.Count; j++)
            {
                intervention[i].woundPhoto[j].createdAt = DateTime.Parse(intervention[i].woundPhoto[j].createdAt.ToString()).ToString("dd.MM.yyyy");
            }
        }
        Interventions = new ObservableCollection<Classes.Intervention>(intervention);
    }

}

My backend:

 try
        {
            var getHistoryWound = await Servicos.Servicos.GetWound(conversations);
            Wound = getHistoryWound;
            if (getHistoryWound != null)
            {
                //As data no formato dd.MM.yyyy data da foto e da proxima intervencao
                DataFoto.Text = DateTime.Parse(getHistoryWound.result.woundDate.ToString()).ToString("dd.MM.yyyy");
                if(getHistoryWound.result.nextIntervention != null)
                    ProximaIntervencao.Text = DateTime.Parse(getHistoryWound.result.nextIntervention.ToString()).ToString("dd.MM.yyyy");

                //O tipo da ferida
                CartaoTituloReport.Text = getHistoryWound.result.intervention[0].typology.ToUpper();

                //Date de admissao
                if (getHistoryWound.result.isPresentOnAdmission)
                    RespostaAdmissao.Text = Languages.AppResources.Sim;
                else
                    RespostaAdmissao.Text = Languages.AppResources.Nao;

                BindingContext = new ViewModels.CarrouselView(getHistoryWound.result.intervention);

                //Caso a ferida esteja fechada, muda a cor da label e o fundo
                if (getHistoryWound.result.isClosed)
                {
                    cartaoFerida.BackgroundColor = Color.FromHex("#FF3A3A3A");
                    LabelEstadoFerida.Text = Languages.AppResources.Fechado;
                    LabelEstadoFerida.TextColor = Color.FromHex("#FF3A3A3A");
                }

                if (getHistoryWound.result.intervention[0].category == "null")
                {
                    Categoria.IsVisible = false;
                    CategoriaLine.IsVisible = false;
                }
                else
                {
                    Categoria.IsVisible = true;
                    CategoriaLine.IsVisible = true;
                    switch (getHistoryWound.result.intervention[0].category)
                    {
                        case "1":
                            CategoriaNivel.Text = "I";
                            break;

                        case "2":
                            CategoriaNivel.Text = "II";
                            break;

                        case "3":
                            CategoriaNivel.Text = "III";
                            break;

                        case "4":
                            CategoriaNivel.Text = "IV";
                            break;

                        case "5":
                            CategoriaNivel.Text = "V";
                            break;
                    }
                }

                //Posicao da imagem
                Carrousel.Position = getHistoryWound.result.intervention.Count - 1;

                //observações da localização
                if(getHistoryWound.result.note == null || getHistoryWound.result.note == "null")
                {
                    CartaoObservacoesLocalizacao.IsVisible = false;
                }
                else
                {
                    CartaoObservacoesLocalizacao.IsVisible = true;
                    var position = getHistoryWound.result.intervention.Count;
                    ObservacoesTitulo.Text = Languages.AppResources.Observacoes + " " + getHistoryWound.result.intervention[position - 1].createdAt.ToString("dd.MM.yyyy");
                    ObservacoesLocalizacao.Text = getHistoryWound.result.note;
                }

                //Maximo da datas
                DataDe.MaximumDate = DateTime.Now;
                DataAte.MaximumDate = DateTime.Now;
                return true;
            }
            return false;
        }
        catch (Exception)
        {
            await DisplayAlert(Languages.AppResources.Notifications, Languages.AppResources.ErrorOccurred, "Ok");
            return false;
        }
1
Could you please align your code properly and add newlines to the attribute definitions so people can actually read it without having to scroll around in every line. What you are asking is that someone finds a bug in your code but the representation of the code makes it cumbersome to do so - Mouse On Mars
A direct gesture recognizor onto a carousel probably won't work, what you should be doing ideally is apply the same logic to your template! i.e. the ViewCell or View in your DataTemplate! - FreakyAli

1 Answers

3
votes

I think your problem is the binding path and source you set is wrong, I wrote a demo and the binding works on my side, here is the code:

<CarouselView>
    <CarouselView.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>Baboon</x:String>
            <x:String>Capuchin Monkey</x:String>
            <x:String>Blue Monkey</x:String>
            <x:String>Squirrel Monkey</x:String>
            <x:String>Golden Lion Tamarin</x:String>
            <x:String>Howler Monkey</x:String>
            <x:String>Japanese Macaque</x:String>
        </x:Array>
    </CarouselView.ItemsSource>

    <CarouselView.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding Path=ViewItemsDetailsCommand}"
                                      CommandParameter="{Binding}"/>
    </CarouselView.GestureRecognizers>
</CarouselView>

And in code behind:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        BindingContext = new CarouselViewModel();
    }
}

public class CarouselViewModel : INotifyPropertyChanged
{
    #region Property

    public event PropertyChangedEventHandler PropertyChanged;
    public Command ViewItemsDetailsCommand => new Command(On_ImageTapped);

    private void On_ImageTapped()
    {
        Console.WriteLine("ouuuuuuuuuuuuuuuuuuuuuuuuuuuu");
    }

    #endregion

    public CarouselViewModel()
    {
    }

}

So, change your binding like below code may work:

  <controls:CarouselViewControl.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding ViewItemsDetailsCommand}"
                                      CommandParameter="{Binding}"/>
    </controls:CarouselViewControl.GestureRecognizers>