【MAUI】自定义横向日期选择控件

文章目录

  • XAML
  • ViewModel

效果是今天永远在最右,顺序请自行调整算法
【MAUI】自定义横向日期选择控件_第1张图片

XAML

        <Grid  Grid.Row="1" RowDefinitions="*,*" Margin="8,20,8,0">
            <CollectionView   ItemsSource="{Binding CalendarDayOfWeeks}" HorizontalOptions="Center">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Frame Grid.Row="1" BackgroundColor="Transparent" VerticalOptions="Center" HorizontalOptions="Center" Padding="0">
                            <Label  Text="{Binding DayText}" TextColor="#A6FFFFFF" FontSize="14" HorizontalOptions="Center">Label>
                        Frame>
                    DataTemplate>
                CollectionView.ItemTemplate>
                <CollectionView.ItemsLayout>
                    <GridItemsLayout Orientation="Vertical" Span="7"/>
                CollectionView.ItemsLayout>
            CollectionView>
            <CollectionView ItemsSource="{Binding CalendarDays}"  HorizontalOptions="Center" Grid.Row="1" x:Name="DayCollectionView">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Frame Grid.Row="1"  BackgroundColor="{Binding DayBgColor}"  CornerRadius="13" VerticalOptions="Center" HorizontalOptions="Center" HeightRequest="26" WidthRequest="26" Padding="0">
                            <VerticalStackLayout VerticalOptions="Center">
                                <Label  Text="{Binding DayText}" TextColor="{Binding DayTextColor}" FontSize="14" HorizontalOptions="Center" VerticalOptions="Center">Label>
                                <Ellipse 
                                   WidthRequest="3"
                                   HeightRequest="3"
                                   BackgroundColor="#FFFFFFFF"
                                   IsVisible="{Binding EventFalgIsVsiable}">Ellipse>
                            VerticalStackLayout>
                            <Frame.GestureRecognizers>
                                <TapGestureRecognizer Command="{Binding BindingContext.DaySelected , Source={Reference DayCollectionView}}" CommandParameter="{Binding .}">TapGestureRecognizer>
                            Frame.GestureRecognizers>
                        Frame>
                    DataTemplate>
                CollectionView.ItemTemplate>
                <CollectionView.ItemsLayout>
                    <GridItemsLayout Orientation="Vertical" Span="7"/>
                CollectionView.ItemsLayout>
            CollectionView>
        Grid>

ViewModel

        private void HorizontalCalendarSelectionDisplay(DateTime dateTime_Selected, bool Flash=false)
        {
            if (Flash)
            {
                #region 动态构造当周
                ObservableCollection<CalendarDay> calendarDays = new ObservableCollection<CalendarDay>();
                DateTime today = DateTime.Now;
                DateTime startOfWeek = new DateTime();
                if (dateTime_Selected.Date == DateTime.Today.Date)//包含当天的把今天放最后
                {
                    startOfWeek = dateTime_Selected.AddDays(-6);
                }
                else
                {
                    //获取所选日期是周几(0代表周日,1代表周一,以此类推)
                    int dayOfWeek = (int)dateTime_Selected.DayOfWeek;
                    if (dayOfWeek == 0) { dayOfWeek = 7; }
                    //计算本周一的日期
                    startOfWeek = dateTime_Selected.AddDays(-dayOfWeek + 1);
                }
                // 遍历本周的每一天
                for (int i = 0; i < 7; i++)
                {
                    var temp = startOfWeek.AddDays(i);
                    //如果没数据 小原点隐藏
                    var calendarEventIsVsiabley = CalendarEventIsVsiabley(temp, startOfWeek, today);
                    if (temp.Date == dateTime_Selected.Date&& temp.Date != today.Date)//选择的但不是当天
                    {
                        calendarDays.Add(new CalendarDay { /*ColumnIndex = i,*/ DayBgColor = "#FF6E73FF", Day = temp.Date, DayText = temp.Day.ToString(), DayTextColor = "#D9FFFFFF", /*DayWidth = width,*/ BgCornerRadius = cornerRadius ,EventFalgIsVsiable= calendarEventIsVsiabley });
                    }
                    else if (temp.Date == today.Date)//当天
                    {
                        calendarDays.Add(new CalendarDay { /*ColumnIndex = i,*/ DayBgColor = "#FF6E73FF", Day = temp.Date, DayText = "今", DayTextColor = "#D9FFFFFF", /*DayWidth = width,*/ BgCornerRadius = cornerRadius, EventFalgIsVsiable = calendarEventIsVsiabley });
                    }
                    else if (temp.Date < today.Date)//当天前
                    {
                        calendarDays.Add(new CalendarDay { /*ColumnIndex = i,*/ DayBgColor = "Transparent", Day = temp.Date, DayText = temp.Day.ToString(), DayTextColor = "#D9FFFFFF", /*DayWidth = width,*/ BgCornerRadius = cornerRadius, EventFalgIsVsiable = calendarEventIsVsiabley });
                    }
                    else//当天后
                    {
                        calendarDays.Add(new CalendarDay { /*ColumnIndex = i,*/ DayBgColor = "Transparent", Day = temp.Date, DayText = temp.Day.ToString(), DayTextColor = "#40FFFFFF", /*DayWidth = width,*/ BgCornerRadius = cornerRadius, EventFalgIsVsiable = calendarEventIsVsiabley });
                    }
                }
                CalendarDays = calendarDays;
                #endregion
            }
            else
            {
                CalendarDays.ForEach(dayOfWeek => { dayOfWeek.DayBgColor = "Transparent"; });
                CalendarDays.First(f => f.Day == dateTime_Selected).DayBgColor = "#FF6E73FF";
            }
        }
        private void HorizontalCalendarSelectionDisplay_Top(DateTime selectedDate)
        {
            #region 动态构造当周几
            ObservableCollection<CalendarDay> calendarDays = new ObservableCollection<CalendarDay>();
            if (selectedDate.Date== DateTime.Today.Date)//包含当天的把今天放最后
            {
                // 循环遍历过去 6 天(包括今天)
                for (int i = 6; i >= 0; i--)
                {
                    // 计算过去的日期
                    DateTime date = selectedDate.AddDays(-i);
                    // 获取这一天是星期几
                    DayOfWeek dayOfWeek = date.DayOfWeek;
                    calendarDays.Add(new CalendarDay { DayText = ObjectHelper.GetChineseDayOfWeek(dayOfWeek), DayTextColor = "#A6FFFFFF" });
                }
                CalendarDayOfWeeks = calendarDays;
            }
            else
            {
                CalendarDayOfWeeks = new ObservableCollection<CalendarDay>
                {
                    new CalendarDay{DayText="周一",DayTextColor="#A6FFFFFF"/*,DayWidth=width*/},
                        new CalendarDay{DayText="周二",DayTextColor="#A6FFFFFF"/*,DayWidth=width*/},
                        new CalendarDay{DayText="周三",DayTextColor="#A6FFFFFF"/*,DayWidth=width*/},
                        new CalendarDay{DayText="周四",DayTextColor="#A6FFFFFF"/*,DayWidth=width*/},
                        new CalendarDay{DayText="周五",DayTextColor="#A6FFFFFF"/*,DayWidth=width*/},
                            new CalendarDay{DayText="周六",DayTextColor="#A6FFFFFF"/*,DayWidth=width*/},
                            new CalendarDay{DayText="周日",DayTextColor="#A6FFFFFF"/*,DayWidth=width*/}
                };
            }
            #endregion
        }
        //缓存查过的数据
        Dictionary<DateTime, List<SleepDiary>> SleepDiaryCatch { get; set; } = new Dictionary<DateTime, List<SleepDiary>>();
        List<SleepDiary> sleepDiaries { get; set; }
        /// 
        /// 返回日期时间原点是否可见
        /// 
        /// 
        public bool CalendarEventIsVsiabley(DateTime dateTime_Selected, DateTime firstDayInWeek, DateTime lastDayInWeek)
        {
            //计算选择日期的首天 判断首天是否存在 是直接取缓存 否则即时查询存入缓存

            if (SleepDiaryCatch.ContainsKey(firstDayInWeek))
            {
                sleepDiaries = SleepDiaryCatch[firstDayInWeek];
            }
            else
            {
                var httpClient = WebApiService.client;
                var temp = httpClient.Post<List<SleepDiary>>(WebApiService.cloudPlatformUri + "/api/app/v1/report/sleepdiary/list", new List<KeyValuePair<string, string>>
                 {
                    new KeyValuePair<string, string>("startTime", firstDayInWeek.ToString("yyyy-MM-dd")),
                    new KeyValuePair<string, string>("endTime",  lastDayInWeek.ToString("yyyy-MM-dd"))
                 });
                if (temp.Code != "success")
                {
                    MainThread.BeginInvokeOnMainThread(async () =>
                    {
                        await Locator.Current.GetService<IDialogService>().ShowToastAsync("获取数据错误");
                    });
                }
                sleepDiaries = temp.Data;
            }
            foreach (var item in sleepDiaries)
            {
                string t = dateTime_Selected.GetTimeStamp().ToString();
                if (SharedMethodService.UnixTimeStampToDateTime(item.recordTime.ToLong()).Date == dateTime_Selected.Date)
                {
                    return true;
                }
            }
            return false;
        }

你可能感兴趣的:(#,跨平台_C#,MAUI)