Range
Range

Reputation: 446

CarouselView in XamarinForms

I'm trying to use the CarouselView in the Xamarin project. But I can’t do it. Here are the installed packages: enter image description here enter image description here Here is the xaml code:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:FlowersStore"
         xmlns:cv="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
         x:Class="FlowersStore.MainPage">

<StackLayout>

    <Grid RowSpacing="0">
        <Grid.RowDefinitions>
            <RowDefinition Height=".3*"/>
            <RowDefinition Height=".7*"/>
        </Grid.RowDefinitions>
        <cv:CarouselView ItemsSource="{Binding Zoos}" x:Name="CarouselZoos">
            <cv:CarouselView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Image Grid.RowSpan="2" Aspect="AspectFill" Source="{Binding ImageUrl}"/>
                        <StackLayout Grid.Row="1" BackgroundColor="#80000000" Padding="12">
                            <Label TextColor="White" Text="{Binding Name}" FontSize="16" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
                        </StackLayout>
                    </Grid>
                </DataTemplate>
            </cv:CarouselView.ItemTemplate>
        </cv:CarouselView>
    </Grid>

</StackLayout>

And here is the c # code:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Xamarin.Forms;

namespace FlowersStore
{
    public class Zoo
    {
        public string ImageUrl { get; set; }
        public string Name { get; set; }
    }

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

        public void LoadDataCatouselView()
        {
            ObservableCollection<Zoo> Zoos = new ObservableCollection<Zoo>
        {
            new Zoo
            {
                ImageUrl = "http://content.screencast.com/users/JamesMontemagno/folders/Jing/media/23c1dd13-333a-459e-9e23-c3784e7cb434/2016-06-02_1049.png",
                Name = "Woodland Park Zoo"
            },
                new Zoo
            {
                ImageUrl =    "http://content.screencast.com/users/JamesMontemagno/folders/Jing/media/6b60d27e-c1ec-4fe6-bebe-7386d545bb62/2016-06-02_1051.png",
                Name = "Cleveland Zoo"
                },
            new Zoo
            {
                ImageUrl = "http://content.screencast.com/users/JamesMontemagno/folders/Jing/media/e8179889-8189-4acb-bac5-812611199a03/2016-06-02_1053.png",
                Name = "Phoenix Zoo"
            }
        };
            CarouselZoos.ItemsSource = Zoos;
        }

    }
}

I use Xamarin Live Player for debugging. The log on the mobile phone displays the following message: [LogEntry: Time=19.11.2018 14:54:54 +03:00, Level=Error, Title=Visualization Error, Message=The given key was not present in the dictionary. (KeyNotFoundException)]

How to fix it? Thanks.

Update 1: I replaced the code based on your advice. I used your advice. I tried to run the application on:

  1. Androind version: 7.1
  2. Emulator: Genymotion Galaxy S7 7.1.0 API 25

And got this error: enter image description here

What it? :(

Upvotes: 0

Views: 1024

Answers (4)

Ivan-San
Ivan-San

Reputation: 843

The problem is with the long path. An easy solution is to move the entire project solution to a shorter path like C:\

Here's an explanation from microsoft: Path Too Long Exception

Upvotes: 3

Ivan-San
Ivan-San

Reputation: 843

Try this
First add this class, for property binding and implement the INotifyPropertyChanged structure to update the view.

public class ViewModelBase : INotifyPropertyChanged
{

    string title = string.Empty;

    /// <summary>
    /// Gets or sets the title.
    /// </summary>
    /// <value>The title.</value>
    public string Title
    {
        get { return title; }
        set { SetProperty(ref title, value); }
    }

    string icon = string.Empty;

    /// <summary>
    /// Gets or sets the icon.
    /// </summary>
    /// <value>The icon.</value>
    public string Icon
    {
        get { return icon; }
        set { SetProperty(ref icon, value); }
    }

    bool isBusy;

    /// <summary>
    /// Gets or sets a value indicating whether this instance is busy.
    /// </summary>
    /// <value><c>true</c> if this instance is busy; otherwise, <c>false</c>.</value>
    public bool IsBusy
    {
        get { return isBusy; }
        set
        {
            SetProperty(ref isBusy, value);
        }
    }


    /// <summary>
    /// Sets the property.
    /// </summary>
    /// <returns><c>true</c>, if property was set, <c>false</c> otherwise.</returns>
    /// <param name="backingStore">Backing store.</param>
    /// <param name="value">Value.</param>
    /// <param name="propertyName">Property name.</param>
    /// <param name="onChanged">On changed.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    protected bool SetProperty<T>(
        ref T backingStore, T value,
        [CallerMemberName]string propertyName = "",
        Action onChanged = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingStore, value))
            return false;

        backingStore = value;
        onChanged?.Invoke();
        OnPropertyChanged(propertyName);
        return true;
    }

    /// <summary>
    /// Occurs when property changed.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;
    /// <summary>
    /// Raises the property changed event.
    /// </summary>
    /// <param name="propertyName">Property name.</param>
    protected void OnPropertyChanged([CallerMemberName]string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Now when you got the base class for bind properties you can add a view model class for bind the properties and follow the MVVM pattern. I think this is the most property way to manipulate the data.

public class Zoo
{
    public string ImageUrl { get; set; }
    public string Name { get; set; }
}

public class CarouselViewModel : ViewModelBase
{
    private ObservableCollection<Zoo> zoos;
    public ObservableCollection<Zoo> Zoos
    {
        get => zoos; set => SetProperty(ref zoos, value);
    }

    public CarouselViewModel()
    {
        zoos = new ObservableCollection<Zoo>
        {
            new Zoo
            {
                ImageUrl = "http://content.screencast.com/users/JamesMontemagno/folders/Jing/media/23c1dd13-333a-459e-9e23-c3784e7cb434/2016-06-02_1049.png",
                Name = "Woodland Park Zoo"
            },
                new Zoo
            {
                ImageUrl =    "http://content.screencast.com/users/JamesMontemagno/folders/Jing/media/6b60d27e-c1ec-4fe6-bebe-7386d545bb62/2016-06-02_1051.png",
                Name = "Cleveland Zoo"
                },
            new Zoo
            {
                ImageUrl = "http://content.screencast.com/users/JamesMontemagno/folders/Jing/media/e8179889-8189-4acb-bac5-812611199a03/2016-06-02_1053.png",
                Name = "Phoenix Zoo"
            }
        };
    }
}
public partial class MainPage : ContentPage
{
    public CarouselViewModel viewModel;
    public MainPage()
    {
        InitializeComponent();
        this.BindingContext = viewModel = new CarouselViewModel();
    }
}

Upvotes: 1

Tom
Tom

Reputation: 1749

In your XAML you have the following line:

<cv:CarouselView ItemsSource="{Binding Zoos}" x:Name="CarouselZoos">

This means that the code is looking to bind a property named Zoos to the ItemsSource property of the CarouselView. You will need to create a property of type List<View> and implement the INotifyPropertyChanged structure to update the view. You'll also need to assign the content page's BindingContext to itself (BindingContext = this;).

You may also find that you cannot simply bind a URL to the Image source, and expect the image to appear.

Upvotes: 2

Sujith Kumar
Sujith Kumar

Reputation: 51

Add the BindingContext=this; after the InitializeComponent(); or else add CarouselZoos.ItemsSource = Zoos; in OnAppearing() method

Upvotes: 1

Related Questions