Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin forms: CarouselView for static content

I am looking for a way to use a CarouselView for Xamarin forms with static content only. That means, I do not intend to use any Itemsource or binding or whatever.

Let's just assume I have three separate Stacklayouts (each of which contains a couple of text labels and buttons) and I want to be able to swipe them horizontally. Something like this (pseudocode):

<cv:CarouselView>
   <cv:CarouselView.Items>
      <CarouselItem>
         <StackLayout>
            <Label Text="This is step1" />
         </StackLayout>
      </CarouselItem >
      <CarouselItem>
         <StackLayout>
            <Label Text="This is step2" />
         </StackLayout>
      </CarouselItem >
      <CarouselItem>
         <StackLayout>
            <Label Text="This is step3" />
         </StackLayout>
      </CarouselItem >
   </cv:CarouselView.Items>
</cv:CarouselView>

Would be nice, if I could just place my content "as it is" not using any dynamic itemsource. Any ideas?

like image 254
Igor P. Avatar asked Feb 08 '18 10:02

Igor P.


1 Answers

You can use data template selectors for selecting which view you want to show.

First, create content views with desired content:

<ContentView.Content>
    <StackLayout>
        <Label Text="Hello Xamarin.Forms!" />
    </StackLayout>
</ContentView.Content>

Then Create a data template selector and in it decide which template should be invoked:

public DataTemplate Step1 { get; set; }
    public DataTemplate Step2 { get; set; }
    public DataTemplate Step3 { get; set; }

    public HelpPageDataTemplateSelector()
    {
        Step1 = new DataTemplate(typeof(ContentViewStep1));
        Step2 = new DataTemplate(typeof(ContentViewStep2));
        Step3 = new DataTemplate(typeof(ContentViewStep3));
    }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        switch ((int)item)
        {
            case 2: return Step2;
            case 3: return Step3;
            default: return Step1;
        }
    }

Then in carousel view, setup data template selector and bind steps as item source (steps in model are just array of integers - 1,2,3 for example):

<ContentPage.Resources>
    <ResourceDictionary>
        <Selector:TemplateSelector x:Key="TemplateSelector"></Selector:HelpPageDataTemplateSelector>
    </ResourceDictionary>
</ContentPage.Resources>

<ContentPage.Content>
    <Forms:CarouselView ItemTemplate="{StaticResource TemplateSelector}" ItemsSource="{Binding Steps}" />
</ContentPage.Content>
like image 63
Ognjen Babic Avatar answered Oct 19 '22 18:10

Ognjen Babic