Category / Section
How to customize the selected month cell in Xamarin.Forms Calendar (SfCalendar)
1 min read
You can customize the selected month cell with a description along with the SelectedDate by using the CellTemplate property of MonthViewSettings and OnMonthCellLoaded event of SfCalendar in Xamarin.Forms.
XAML
The CellTemplate is defined with the circle by Frame and description by Label. The selection is handled by the IsSelected property from ViewModel.
<StackLayout> <calendar:SfCalendar x:Name="calendar" ShowNavigationButtons="True" ShowYearView="False"> <calendar:SfCalendar.MonthViewSettings> <calendar:MonthViewSettings DateTextAlignment="Center" CellGridOptions="None" DateSelectionColor="Transparent" TodaySelectionBackgroundColor="Transparent" > <calendar:MonthViewSettings.CellTemplate> <DataTemplate> <Grid > <Label FontSize="13" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" Text="{Binding DayNumber}" TextColor="{Binding SelectedTextColor}" /> <Frame IsVisible="{Binding IsSelected}" Padding="7.25" BorderColor="Blue" BackgroundColor="Blue" CornerRadius="28" HeightRequest="100" WidthRequest="100" VerticalOptions="Center" HorizontalOptions="Center"> <Grid > <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Label Grid.Row="0" FontSize="13" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" Text="{Binding DayNumber}" TextColor="{Binding TextColor}" /> <Label Grid.Row="1" FontSize="13" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" BackgroundColor="Blue" Text="Test" TextColor="{Binding TextColor}"/> </Grid> </Frame> </Grid> </DataTemplate> </calendar:MonthViewSettings.CellTemplate> </calendar:MonthViewSettings> </calendar:SfCalendar.MonthViewSettings> </calendar:SfCalendar> </StackLayout>
C#
The CellBindingContext is updated in the OnMenthCellLoaded event based on the SelectedDate.
private void Calendar_OnMonthCellLoaded(object sender, MonthCellLoadedEventArgs e) { var viewModel = GetDayModelFor(e.Date, calendar); e.CellBindingContext = viewModel; } public CalendarViewModel GetDayModelFor(DateTime date, SfCalendar calendar) { var selectedDate = (DateTime)calendar.SelectedDate; var selected = calendar.SelectedDate != null && date.Month == selectedDate.Month && date.Year == selectedDate.Year && date.Day == selectedDate.Day; return new CalendarViewModel() { Date = date.Date, IsSelected = selected, SelectedTextColor = selected ? Color.Yellow : Color.Black, }; }
Output