如何在WinUI 3的CalendarView控件中隐藏并禁用非当月日期?
禁用WinUI 3 CalendarView中的非当月超范围日期
方法一:通过SelectionChanged事件拦截无效选择
先在XAML中为CalendarView绑定选择变更事件:
<CalendarView x:Name="TargetCalendar" SelectionChanged="TargetCalendar_SelectionChanged"/>
然后在后台代码中实现拦截逻辑,判断选中日期是否属于当前显示月份,若超出范围则移除选中状态:
private void TargetCalendar_SelectionChanged(CalendarView sender, CalendarViewSelectionChangedEventArgs args) { var displayDate = sender.DisplayDate ?? DateTime.Now; var monthStart = new DateTime(displayDate.Year, displayDate.Month, 1); var monthEnd = monthStart.AddMonths(1).AddDays(-1); foreach (var date in args.AddedItems) { if (date < monthStart || date > monthEnd) { sender.SelectedDates.Remove(date); } } }
方法二:自定义样式直接禁用超范围项
如果需要从UI层面直接禁用(不可点击+视觉灰显),可以修改CalendarViewItem的样式,结合IsOutOfScope属性控制启用状态:
- 先在页面资源中添加布尔取反转换器(因为
IsOutOfScope为true时需要禁用控件):
<Page.Resources> <local:BoolNegationConverter x:Key="BoolNegationConverter"/> </Page.Resources>
- 实现转换器类:
public class BoolNegationConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) => value is bool val ? !val : value; public object ConvertBack(object value, Type targetType, object parameter, string language) => value is bool val ? !val : value; }
- 为CalendarView设置ItemContainerStyle:
<CalendarView x:Name="TargetCalendar"> <CalendarView.ItemContainerStyle> <Style TargetType="CalendarViewItem"> <Setter Property="IsEnabled" Value="{Binding IsOutOfScope, RelativeSource={RelativeSource Self}, Converter={StaticResource BoolNegationConverter}}"/> <!-- 配合视觉隐藏:将超范围日期前景色设为背景色 --> <Setter Property="OutOfScopeForeground" Value="{ThemeResource SystemControlPageBackgroundChromeLowBrush}"/> </Style> </CalendarView.ItemContainerStyle> </CalendarView>
这样设置后,非当月的超范围日期会直接处于禁用状态,无法被选中,同时视觉上也会和背景融合。
内容的提问来源于stack exchange,提问作者Bevara Satyasairam
相关产品推荐
相关产品推荐

