Category / Section
How to use Nito.MVVM in Xamarin.Forms Accordion (SfAccordion)
2 mins read
You can use Nito.MVVM in Xamarin.Forms SfAccordion. Please refer to the steps below to work with Nito.MVVM,
STEP 1: Install the Nito.MVVM.Async Nuget package to the shared code project.
STEP 2: Define the AsyncCommand to populate the data in the ViewModel.
namespace AccordionXamarin { public class ItemInfoRepository : INotifyPropertyChanged { public IAsyncCommand LoadDataCommand { get; set; } public ItemInfoRepository() { LoadDataCommand = new AsyncCommand(ExecuteLoadData); } private async Task ExecuteLoadData(object args) { ... } } }
STEP 3:
- Populate asynchronous data for the Accordion in the LoadData method.
- In the command execution method, invoke the LoadData method in the NotifyTask.Create method that executes the LoadData action asynchronously.
- You can get the populated data from the NotifyTask.Result. If the task is completed, set the result to the collection.
- Invoke the PropertyChanged event to notify the collection update.
namespace AccordionXamarin { public class ItemInfoRepository : INotifyPropertyChanged { public ObservableCollection<ItemInfo> Info { get; set; } private async Task ExecuteLoadData(object args) { var notifyTask = NotifyTask.Create(LoadData); if (notifyTask.IsCompleted) { Info = notifyTask.Result as ObservableCollection<ItemInfo>; OnPropertyChanged(nameof(Info)); } } private async Task<ObservableCollection<ItemInfo>> LoadData() { var info = new ObservableCollection<ItemInfo> { new ItemInfo() { Name = "Cheese burger", Description = "Hamburger accompanied with melted cheese. The term itself is a portmanteau of the words cheese and hamburger. The cheese is usually sliced, then added a short time before the hamburger finishes cooking to allow it to melt." }, ... }; return info; } } }
STEP 4: Bind the ViewModel collection to the BindableLayout.ItemsSource of the Accordion.
<StackLayout> <Button Text="Load Accordion" Command="{Binding LoadDataCommand}" HeightRequest="50"/> <accordion:SfAccordion x:Name="accordion" BindableLayout.ItemsSource="{Binding Info}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" ExpandMode="SingleOrNone"> <BindableLayout.ItemTemplate> <DataTemplate> <accordion:AccordionItem> <accordion:AccordionItem.Header> <Grid> <Label TextColor="#495F6E" Text="{Binding Name}" VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="50" VerticalTextAlignment="Center"/> </Grid> </accordion:AccordionItem.Header> <accordion:AccordionItem.Content> <Grid BackgroundColor="#e8e8e8" Padding="5,0,0,0"> <Label Text="{Binding Description}" VerticalOptions="Center"/> </Grid> </accordion:AccordionItem.Content> </accordion:AccordionItem> </DataTemplate> </BindableLayout.ItemTemplate> </accordion:SfAccordion> </StackLayout>