1

I want to make a xamarin forms carousel view containing 2 custom views. I have this code:

<ContentPage x:Class="MainView" xmlns:mvvm="clr-namespace:Prism.Mvvm;assembly=Prism.Forms" xmlns:views="clr-namespace:Views" x:Name="Main">
<CarouselView>
    <CarouselView.ItemsSource>
        <x:Array Type="{x:Type View}">
            <views:View1  mvvm:ViewModelLocator.AutowirePartialView="{x:Reference Main}" />
            <views:View2 mvvm:ViewModelLocator.AutowirePartialView="{x:Reference Main}" />
        </x:Array>
    </CarouselView.ItemsSource>
    <CarouselView.ItemTemplate>
        <DataTemplate>
            <ContentView Content="{Binding .}" />
        </DataTemplate>
    </CarouselView.ItemTemplate>
</CarouselView>
</ContentPage>

When launching the app, exception is thrown:

Xamarin.Forms.Xaml.XamlParseException: 'Position 80:37. Can not find the object referenced by Main'

If I just set both views as direct content of the main page, it works fine. What am I doing wrong? Is there a way to make the collection of views through the MainViewModel?

Esteban Chornet
  • 928
  • 3
  • 14
  • 38
  • I am not confident about your scenario. But where is the reference for Main? Is it in the MainPage? I don't find any view with x:name="Main" – Nikhileshwar Jan 09 '20 at 10:00
  • Yes, ... carousel ... – Esteban Chornet Jan 09 '20 at 10:02
  • 2
    `... make the collection of views through the MainViewModel...` - you do _not_ want to do that. Make a collection of view models instead and map to data templates. – Haukinger Jan 09 '20 at 10:19
  • And how do I map each view to their own viewModel in the carousel? – Esteban Chornet Jan 09 '20 at 10:27
  • 1
    I guess what Haukinger said makes sense and regarding mapping the View to item. You could use a DataTemplateSelector. [MSDocs link for ItemTemplate selector](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/carouselview/populate-data#choose-item-appearance-at-runtime). The API `ItemTemplateSelector` is not present in `CarouselView` as in `ListVew`. `ItemTemplate` itself takes DataTemplateSelector object. – Nikhileshwar Jan 09 '20 at 12:02
  • 1
    Yes, use [datatemplateselector](https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.datatemplateselector?view=xamarin-forms) to choose item appearance at runtime and binding to corresponding model in itemSource. – nevermore Jan 10 '20 at 02:39

0 Answers0