Mr.*_*per 3 c# xaml templates carousel xamarin.forms
我需要在 Xamarin 表单中制作 CarouselView,其中每张幻灯片都有一个特定的模板。目前我已经这样做了:
XAML:
xmlns:control="clr-namespace:Xamarin.Forms;assembly=Xamarin.Forms.CarouselView"
.......
<ContentView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<control:CarouselView x:Name="carouselView">
<control:CarouselView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Testo}" />
</DataTemplate>
</control:CarouselView.ItemTemplate>
</control:CarouselView>
</ContentView>
Run Code Online (Sandbox Code Playgroud)
代码隐藏:
List<CustomCell> myCarousel = new List<CustomCell>();
myCarousel.Add(new CustomCell { Testo = "ciao" });
myCarousel.Add(new CustomCell { Testo = "ciao due" });
carouselView.ItemsSource = myCarousel;
Run Code Online (Sandbox Code Playgroud)
自定义单元格:
public class CustomCell
{
public string Testo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
所有这些都有效,我的问题是我会为每张幻灯片使用不同的模板,例如,每张幻灯片在图形上不同的网格,这是因为我必须以不同的方式以图形方式显示数据。你能推荐一个解决方案吗?谢谢
小智 6
您可以使用数据模板选择器自定义 CarouselView 中不同项目的外观。一个简单的例子:
MyDataTemplateSelector.cs
public class MyDataTemplateSelector : DataTemplateSelector
{
public DataTemplate SimpleTemplate { get; set; }
public DataTemplate ComplexTemplate { get; set; }
public MyDataTemplateSelector()
{
SimpleTemplate = new DataTemplate(typeof(SimpleView));
ComplexTemplate = new DataTemplate(typeof(ComplexView));
}
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
CustomCell cell = (CustomCell)item;
if (cell.Testo.Length > 5) {
return ComplexTemplate;
} else {
return SimpleTemplate;
}
}
}
Run Code Online (Sandbox Code Playgroud)
简单视图.xaml
<ContentView>
<StackLayout BackgroundColor="Red">
<Label Text="{Binding Testo}" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentView>
Run Code Online (Sandbox Code Playgroud)
复杂视图.xaml
<ContentView>
<StackLayout BackgroundColor="Yellow" >
<Label Text="{Binding Testo}" VerticalOptions="CenterAndExpand" HorizontalOptions="Center" />
<Label Text="I lied about this being complex" />
</StackLayout>
</ContentView>
Run Code Online (Sandbox Code Playgroud)
在 CarouselView 所在的页面中:
<ContentPage.Resources>
<ResourceDictionary>
<local:MyDataTemplateSelector x:Key="templateSelector"></local:MyDataTemplateSelector>
</ResourceDictionary>
</ContentPage.Resources>
....
<control:CarouselView x:Name="carouselView" ItemTemplate="{StaticResource templateSelector}" />
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5811 次 |
最近记录: |