A Microsoft framework for building cross-platform mobile apps using .NET and C# with native performance and user interfaces.
Hello @CB1216 ,
Welcome to our Microsoft Q&A platform!
This last page would be something that is always there and dropped in when the carousel loop has finished no matter how many pages of it there are.
CarouserlView supports to choose item appearance at runtime, try using a DataTemplateSelector object to specify different template for the last item. Please add a bool parameter to the Model class as the indentifier.
Check the code:
Custom templateSelector class
public class CustomDataTemplateSelector : DataTemplateSelector
{
public DataTemplate NormalTemplate { get; set; }
public DataTemplate LastItemTemplate { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
return ((TestModel)item).IsTheLast ? LastItemTemplate : NormalTemplate;
}
}
When you add a new item to the data collection, update the indentifier's value of the items.
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="normal_template">
...
</DataTemplate>
<DataTemplate x:Key="lastItem_template">
<StackLayout>
<Label Text="Complete"/>
<Button Text="Go to previous page" .../>
</StackLayout>
</DataTemplate>
<local:CustomDataTemplateSelector x:Key="the_selector"
NormalTemplate="{x:StaticResource normal_template}"
LastItemTemplate="{x:StaticResource lastItem_template}"/>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<Button Clicked="Button_Clicked" Text="Add Item"/>
<CarouselView x:Name="carousel"
ItemsSource="{Binding DataCollection}"
ItemTemplate="{DynamicResource the_selector}"/>
</StackLayout>
</ContentPage.Content>
public partial class TestPage : ContentPage
{
TestViewModel viewModel;
ObservableCollection<TestModel> dataCollection;
public TestPage()
{
InitializeComponent();
viewModel = new TestViewModel();
dataCollection = viewModel.DataCollection;
BindingContext = viewModel;
}
private async void Button_Clicked(object sender, EventArgs e)
{
foreach (TestModel item in dataCollection)
{
item.IsTheLast = false;
}
dataCollection.Add(new TestModel { ..., IsTheLast = true });
}
}
Check the doc: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/carouselview/populate-data#choose-item-appearance-at-runtime
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.