如何在XamForms Calendar中高亮显示SQLite存储的生日日期
实现方案
完全可以实现,你使用的XamForms.Controls.Calendar组件原生支持通过SpecialDates属性配置高亮特殊日期,按以下步骤修改即可:
步骤1:修改XAML代码,给Calendar组件命名
找到你首页XAML中的Calendar节点,添加x:Name属性,同时删除原有的错误SpecialDates绑定(原绑定直接绑Date字段不符合组件要求):
<controls:Calendar x:Name="birthdayCalendar" DatesBackgroundColor="{AppThemeBinding Dark=Black, Light=White}" DatesTextColor="{AppThemeBinding Dark=White, Light=Black}" BackgroundColor="{AppThemeBinding Dark=Black, Light=White}" Padding="10,0,10,0" SelectedBorderWidth="4" DisabledBorderColor="Black" ShowNumberOfWeek="false" StartDay="Sunday" TitleLabelTextColor="Purple" TitleLeftArrowTextColor="MediumVioletRed" TitleRightArrowTextColor="MediumVioletRed" DateCommand="{Binding DateChosen}" />
步骤2:修改后台OnAppearing逻辑,加载高亮日期
首先在MainPage.xaml.cs的顶部引入组件命名空间:
using XamForms.Controls;
然后修改OnAppearing方法,在查询到生日数据后,构造特殊日期集合赋值给Calendar:
protected override void OnAppearing() { base.OnAppearing(); using(SQLiteConnection conn = new SQLiteConnection(App.FilePath)) { conn.CreateTable<Birthdays>(); var birthdayList = conn.Table<Birthdays>().ToList(); birthdayListView.ItemsSource = birthdayList; // 构造高亮日期集合,样式可按需调整 var highlightDates = birthdayList.Select(b => new SpecialDate(b.Date) { BackgroundColor = Color.LightCoral, TextColor = Color.White, Selectable = true }).ToList(); // 赋值给日历组件 birthdayCalendar.SpecialDates = highlightDates; } }
可选优化:实现生日每年重复高亮
如果需要生日每年的同月同日都高亮,不需要每年重新录入,可以修改逻辑结合日历显示的年份动态生成高亮日期:
首先给Calendar组件添加MonthChanged事件:
<controls:Calendar x:Name="birthdayCalendar" MonthChanged="BirthdayCalendar_MonthChanged" ... 其余原有属性保持不变 />
然后后台添加对应处理逻辑:
private List<Birthdays> _allBirthdays; protected override void OnAppearing() { base.OnAppearing(); using(SQLiteConnection conn = new SQLiteConnection(App.FilePath)) { conn.CreateTable<Birthdays>(); _allBirthdays = conn.Table<Birthdays>().ToList(); birthdayListView.ItemsSource = _allBirthdays; UpdateHighlightDates(birthdayCalendar.CurrentDate.Year); } } private void BirthdayCalendar_MonthChanged(object sender, MonthChangedEventArgs e) { // 切换月份时更新当前年份的高亮生日 UpdateHighlightDates(e.NewDate.Year); } private void UpdateHighlightDates(int targetYear) { var highlightDates = _allBirthdays.Select(b => new SpecialDate(new DateTime(targetYear, b.Date.Month, b.Date.Day)) { BackgroundColor = Color.LightCoral, TextColor = Color.White, Selectable = true }).ToList(); birthdayCalendar.SpecialDates = highlightDates; }
小提示:现有代码中
Birthdays brithday = new Birthdays()的变量名存在拼写错误,可后续修正为birthday避免维护混淆。
内容的提问来源于stack exchange,提问作者Jesse Webb
相关产品推荐
相关产品推荐

