首页 > 代码库 > WPF--Calendar控件高级使用

WPF--Calendar控件高级使用

一、得到当前显示的月份:

      DateTime SelectedDay = this.MC.DisplayDate;

二、得到当前选中的天,得到当前选中的周,得到当前显示的月份:

      如果你使用系统默认的事件SelectedDateChanged是很难获取焦点的,给Calendar注册MC_MouseLeftButtonUp事件

      

1  //在初始化时注册事件2  MC.AddHandler(Button.MouseLeftButtonDownEvent, new RoutedEventHandler(MC_MouseLeftButtonUp), true);3 4 private void MC_MouseLeftButtonUp(object sender, RoutedEventArgs e)

事件的关键代码:

 1 if (sender is Calendar) 2 { 3     if (MC.InputHitTest(Mouse.GetPosition(e.Source as FrameworkElement)) is TextBlock) 4     { 5         TextBlock tb = MC.InputHitTest(Mouse.GetPosition(e.Source as FrameworkElement)) 6  as TextBlock;//本行代码是个关键,使用了WPF内置的碰撞检测 7         if (tb != null) 8         { 9 10             try11             {12                 //获取选择的是哪一天13                 int.Parse(tb.Text);14             }15        16        catch (Exception ex) //Click The WeekDaysButton17        {18 19                  //获取选择的是星期几,如果点击“周1、周2、...周7”按钮,程序会走到此处来得出星期几。20           int indexofWeek = (tb.Parent as Grid).Children.IndexOf(tb);21                  //次方法能获取切换月份按钮后的当前月份22                  DateTime SelectedDay = this.MC.DisplayDate;23        }24         }25     }26 }

 三、自定义日期的背景颜色

3.1、首先要自定义几个类,用于模板转换

 1   public class CustemItems 2     { 3         bool isSpecific; 4  5         public bool IsSpecific 6         { 7             get { return isSpecific; } 8             set { isSpecific = value; } 9         }10 11         DateTime d;12 13         public DateTime Dete14         {15             get { return d; }16             set { d = value; }17         }18         string s;19 20         public string StrOfColor21         {22             get { return s; }23             set { s = value; }24         }25         public CustemItems(DateTime d, string str)26         {27             Dete = d;28             StrOfColor = str;29         }30     }
 1 public class BlueLetterDayConverter : IValueConverter 2     { 3         public static List<CustemItems> dict = new List<CustemItems>(); 4         5  6         static BlueLetterDayConverter() 7         { 8              9         }10 11         public object Convert(object value, Type targetType,12                               object parameter, CultureInfo culture)13         {14             string text = null;15             for (int i = 0; i < dict.Count; i++)16             {17                 if (dict[i].Dete == (DateTime)value)18                 {19                     text = dict[i].StrOfColor;20                 }21             }22 23             return text;24         }25 26         public object ConvertBack(object value, Type targetType,27                                   object parameter, CultureInfo culture)28         {29             return null;30         }31         public void Add(DateTime date, string str)32         {33             dict.Add(new CustemItems(date, str));34         }35 36         public static void Update(List<CustemItems> MIList)37         {38             dict.Clear();39             dict = MIList;40         }41 42     }
public class RedLetterDayConverter : IValueConverter    {        public static List<CustemItems> dict = new List<CustemItems>();               static RedLetterDayConverter()        {                   }        public object Convert(object value, Type targetType,                              object parameter, CultureInfo culture)        {            string text = null;            for (int i = 0; i < dict.Count; i++)            {                if (dict[i].Dete == (DateTime)value)                {                    text = dict[i].StrOfColor;                }            }            return text;        }        public object ConvertBack(object value, Type targetType,                                  object parameter, CultureInfo culture)        {            return null;        }        public void Add(DateTime date, string str)        {            dict.Add(new CustemItems(date, str));        }        public static void Update(List<CustemItems> MIList)        {            dict.Clear();            dict = MIList;        }    }

3.2 Calendar模板的定义

 1   <Calendar x:Name="MC" HorizontalAlignment="Left" VerticalAlignment="Top"  2                   MouseLeftButtonDown="MC_MouseLeftButtonUp" 3                  > 4             <Calendar.CalendarDayButtonStyle> 5                 <Style TargetType="{x:Type CalendarDayButton}"> 6                     <Setter Property="Template"> 7                         <Setter.Value> 8                             <ControlTemplate TargetType="{x:Type CalendarDayButton}" x:Name="CalendarDayButtonControlTemplate"> 9                                 <ControlTemplate.Resources>10                                     <src:RedLetterDayConverter x:Key="convRed" />11                                     <src:BlueLetterDayConverter x:Key="convBlue" />12                                 </ControlTemplate.Resources>13                                 <Grid>14                                     <Rectangle x:Name="RedLetterDayBackground" IsHitTestVisible="False" Fill="Red"/>15                                     <Rectangle x:Name="BlueLetterDayConverter" IsHitTestVisible="False" Fill="Blue"/>16 17                                     <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 18                                                       VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="5,1,5,1"/>19                                 </Grid>20                                 <ControlTemplate.Triggers>21                                     <DataTrigger Binding="{Binding Converter={StaticResource convRed}}"  Value=http://www.mamicode.com/"{x:Null}">22                                         <Setter TargetName="RedLetterDayBackground" Property="Visibility" Value=http://www.mamicode.com/"Hidden" />23                                     </DataTrigger>24                                     <DataTrigger Binding="{Binding Converter={StaticResource convBlue}}"  Value=http://www.mamicode.com/"{x:Null}">25                                         <Setter TargetName="BlueLetterDayConverter" Property="Visibility" Value=http://www.mamicode.com/"Hidden" />26                                     </DataTrigger>27                                 </ControlTemplate.Triggers>28                             </ControlTemplate>29                         </Setter.Value>30                     </Setter>31                 </Style>32             </Calendar.CalendarDayButtonStyle>33 34         </Calendar>
View Code

3.3 更新转换模板的List

 1 List<CustemItems> ItemListRed = new List<CustemItems>(); 2 List<CustemItems> ItemListBule = new List<CustemItems>(); 3  4 ... 5  6 RedLetterDayConverter.Update(ItemListRed); 7 BlueLetterDayConverter.Update(ItemListBule); 8 if (!StartTimer) 9 {10     dispatcherTimer.Start();11  }

 

3.4 重点:

  因为从根本上讲ControlTemplate.Resources是一个静态的资源,它无法做到资源变更后,系统自动会通知控件(或者控件模板)去更新对应的UI显示,这个在《WPF程序设计指南[Charles Petzold]》书中的第535页至539页有详细介绍。所以我们要在变更RedLetterDayConverter 或者BlueLetterDayConverter里面的List<>对象以后,需要使用一个Timer去手动更新UI,从而触发模板的更新。 

 

1 void dispatcherTimer_Tick(object sender, EventArgs e)2         {3             StartTimer = true;4             MC.DisplayDate = MC.DisplayDate.AddMonths(1);5             MC.DisplayDate = MC.DisplayDate.AddMonths(-1);6             Thread.Sleep(50);7             dispatcherTimer.Stop();8             StartTimer = false;9         }

 

完整的例子:

下载连接