首页 > 解决方案 > Xamarin Forms:如何使每个轮播页面具有不同的颜色

问题描述

我创建了包含幻灯片集合的轮播视图。每张幻灯片都包含图像、消息和颜色。它存储在 ObservableCollection 中。我的系列有三种颜色。第一张幻灯片/页面应该是黄色的,第二张应该是红色的,第三张应该是蓝色的。我遇到的问题是,当应用程序启动时,轮播中的所有幻灯片都是蓝色的。我需要每张幻灯片/页面都有不同的颜色。

 Carousel.ItemsSource =   slides = new ObservableCollection<Slides>(new[]
            {
                new Slides("money", "Some Description", BackgroundColor = Color.Yellow),
                new Slides("money", "Some Description2", BackgroundColor = Color.Red),
                new Slides("money", "Some Description3",BackgroundColor = Color.Blue)});



<Control:CarouselViewControl x:Name="Carousel"
                             ShowIndicators="True"
                             BackgroundColor="{Binding Color}"
                             CurrentPageIndicatorTintColor="Black">
   <Control:CarouselViewControl.ItemTemplate>
       <DataTemplate>
      <Grid>
          <Grid.RowDefinitions>
              <RowDefinition Height="*"/>
              <RowDefinition Height="*"/>
          </Grid.RowDefinitions>
          <ContentView Grid.Row="0" Padding="60,30,60,0">
              <Image Source="{Binding Image}" Aspect="AspectFit"/>
          </ContentView>
          <ContentView Grid.Row="1" Padding="20,50,20,0">
              <Label Text="{Binding Message}" TextColor="black"
                     HorizontalOptions="CenterAndExpand"
                     FontSize="Large"/>

          </ContentView>

      </Grid>

       </DataTemplate>
   </Control:CarouselViewControl.ItemTemplate>
</Control:CarouselViewControl>

我希望每一页都有不同的颜色。

标签: formsxamarincarousel

解决方案


您正在绑定BackgroundColorfor CarouselViewControl,这将为整个视图设置它,而不是为不同的幻灯片设置它。

此外,存储在 中的项目ItemsSource不代表 中的任何视图CarouselViewControl,而是代表数据对象。仅仅因为ItemsSource集合中的一个对象有一个值BackgroundColorBackgroundColor相应视图中的CarouselViewControl不是自动设置的。

要设置页面的背景,您必须在 中操作并将 的属性DataTemplate绑定到 的相应属性。BackgroundColorGridSlide

<DataTemplate>
  <Grid BackgroundColor="{Binding BackgroundColor}"> <!-- Bind the grids BackgroundColor to the one of the Slide -->
    <!-- the grids content -->
  </Grid>
</DataTemplate>

推荐阅读