Calendar with week number
The current calendar not allow to show week number, i have made somes update for show it like this (datepicker too)
you must create an attached property
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
public static class CalendarHelper { #region ShowWeekNumber public static bool GetShowWeekNumber(DependencyObject obj) => (bool)obj.GetValue(ShowWeekNumberProperty); public static void SetShowWeekNumber(DependencyObject obj, bool value) => obj.SetValue(ShowWeekNumberProperty, value); public static readonly DependencyProperty ShowWeekNumberProperty = DependencyProperty.RegisterAttached("ShowWeekNumber", typeof(bool), typeof(CalendarHelper), new PropertyMetadata(false , (ss, ee) => { if(ss is System.Windows.Controls.Calendar ca) { ca.Loaded += (s, e) => { // get grid with name var x = ca.FindChild<Grid>("PART_WeekNumber"); if (x != null) { EventHandler<CalendarDateChangedEventArgs> changed = (a, b) => { // get first day of month var dref = new DateTime(ca.DisplayDate.Year, ca.DisplayDate.Month,1); // adjuste date if first days is monday if(dref.DayOfWeek == DayOfWeek.Monday) { dref = dref.AddDays(-1); } x.Children.Clear(); for (int row = 1; row <= 6; row++, dref= dref.AddDays(7)) { var tb = new TextBlock() { Text = GetWeekNumber(dref).ToString(), FontSize = 10, Margin = new Thickness(0, -2, 0, 0), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, Foreground = Brushes.Gray, }; Grid.SetRow(tb, row); x.Children.Add(tb); } }; ca.DisplayDateChanged += (sss, eee) => { changed(null, null); }; changed(null, null); } }; } })); #endregion public static int GetWeekNumber(DateTime from) { CultureInfo ciCurr = CultureInfo.CurrentCulture; return ciCurr.Calendar.GetWeekOfYear(from, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } public static T FindChild<T>(this DependencyObject parent, string childName) where T : DependencyObject { // Confirm parent and childName are valid. if (parent == null) return null; T foundChild = null; Debug.WriteLine($"ELEMENT TYPE = {parent.GetType()} -> {(parent as FrameworkElement).Name} #{VisualTreeHelper.GetChildrenCount(parent)}"); int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); // If the child is not of the request child type child T childType = child as T; if (childType == null) { // recursively drill down the tree foundChild = FindChild<T>(child, childName); // If the child is found, break so we do not overwrite the found child. if (foundChild != null) break; } else if (!string.IsNullOrEmpty(childName)) { var frameworkElement = child as FrameworkElement; // If the child's name is set for search if (frameworkElement != null && frameworkElement.Name == childName) { // if the child's name is of the request name foundChild = (T)child; break; } else { // recursively drill down the tree foundChild = FindChild<T>(child, childName); // If the child is found, break so we do not overwrite the found child. if (foundChild != null) break; } } else { // child element found. foundChild = (T)child; break; } } return foundChild; } } |
and made corrections in style
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
<!-- CALENDAR --> <Style TargetType="{x:Type Calendar}"> <Setter Property="CalendarItemStyle" Value="{DynamicResource CalendarItemStyle1}" /> <Setter Property="local:CalendarHelper.ShowWeekNumber" Value="true" /> </Style> <!-- CALENDAR ITEM --> <Style x:Key="CalendarItemStyle1" TargetType="{x:Type CalendarItem}"> <Setter Property="Margin" Value="0,3,0,3" /> <Setter Property="Background" Value="green" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type CalendarItem}"> <ControlTemplate.Resources> <DataTemplate x:Key="{x:Static CalendarItem.DayTitleTemplateResourceKey}"> <TextBlock Foreground="#FF333333" FontFamily="Verdana" FontWeight="Bold" FontSize="9.5" HorizontalAlignment="Center" Margin="0,6,0,6" Text="{Binding}" VerticalAlignment="Center" /> </DataTemplate> </ControlTemplate.Resources> <Grid x:Name="PART_Root"> <Grid.Resources> <SolidColorBrush x:Key="DisabledColor" Color="#A5FFFFFF" /> </Grid.Resources> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Duration="0" Storyboard.TargetName="PART_DisabledVisual" To="1" Storyboard.TargetProperty="Opacity" /> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1"> <Border BorderBrush="#FFFFFFFF" BorderThickness="2" CornerRadius="1"> <Grid> <Grid.Resources> <ControlTemplate x:Key="PreviousButtonTemplate" TargetType="{x:Type Button}"> <Grid Cursor="Hand"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimation Duration="0" Storyboard.TargetName="path" To="#FF73A9D8" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" /> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Duration="0" Storyboard.TargetName="path" To=".5" Storyboard.TargetProperty="(Shape.Fill).(Brush.Opacity)" /> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Rectangle Fill="#11E5EBF1" Opacity="1" Stretch="Fill" /> <Grid> <Path x:Name="path" Data="M288.75,232.25 L288.75,240.625 L283,236.625 z" Fill="#FF333333" HorizontalAlignment="Left" Height="10" Margin="14,-6,0,0" Stretch="Fill" VerticalAlignment="Center" Width="6" /> </Grid> </Grid> </ControlTemplate> <ControlTemplate x:Key="NextButtonTemplate" TargetType="{x:Type Button}"> <Grid Cursor="Hand"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimation Duration="0" Storyboard.TargetName="path" To="#FF73A9D8" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" /> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Duration="0" Storyboard.TargetName="path" To=".5" Storyboard.TargetProperty="(Shape.Fill).(Brush.Opacity)" /> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Rectangle Fill="#11E5EBF1" Opacity="1" Stretch="Fill" /> <Grid> <Path x:Name="path" Data="M282.875,231.875 L282.875,240.375 L288.625,236 z" Fill="#FF333333" HorizontalAlignment="Right" Height="10" Margin="0,-6,14,0" Stretch="Fill" VerticalAlignment="Center" Width="6" /> </Grid> </Grid> </ControlTemplate> <ControlTemplate x:Key="HeaderButtonTemplate" TargetType="{x:Type Button}"> <Grid Cursor="Hand"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimation Duration="0" Storyboard.TargetName="buttonContent" To="#FF73A9D8" Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)" /> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Duration="0" Storyboard.TargetName="buttonContent" To=".5" Storyboard.TargetProperty="Opacity" /> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <ContentPresenter x:Name="buttonContent" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" TextElement.Foreground="#FF333333" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="1,4,1,9" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" /> </Grid> </ControlTemplate> </Grid.Resources> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Button x:Name="PART_PreviousButton" Grid.Column="0" Focusable="False" HorizontalAlignment="Left" Height="20" Grid.Row="0" Template="{StaticResource PreviousButtonTemplate}" Width="28" /> <Button x:Name="PART_HeaderButton" Grid.Column="1" Focusable="False" FontWeight="Bold" FontSize="10.5" HorizontalAlignment="Center" Grid.Row="0" Template="{StaticResource HeaderButtonTemplate}" VerticalAlignment="Center" /> <Button x:Name="PART_NextButton" Grid.Column="2" Focusable="False" HorizontalAlignment="Right" Height="20" Grid.Row="0" Template="{StaticResource NextButtonTemplate}" Width="28" /> <Grid Grid.ColumnSpan="3" HorizontalAlignment="Center" Margin="6,-1,6,6" Grid.Row="1" x:Name="PART_MonthView0" Grid.IsSharedSizeScope="true"> <Border x:Name="br" Grid.Column="0" Margin="6 20 0 10" BorderThickness="1 0 0 0" BorderBrush="gray" Visibility="Collapsed"/> <Grid x:Name="PART_WeekNumber" Visibility="Collapsed" Background="Transparent" Width="10" VerticalAlignment="Stretch" HorizontalAlignment="Left" Margin=" -7 0 0 0"> <Grid.RowDefinitions> <RowDefinition Height="Auto" SharedSizeGroup="A" /> <RowDefinition Height="Auto" SharedSizeGroup="B" /> <RowDefinition Height="Auto" SharedSizeGroup="C" /> <RowDefinition Height="Auto" SharedSizeGroup="D" /> <RowDefinition Height="Auto" SharedSizeGroup="E" /> <RowDefinition Height="Auto" SharedSizeGroup="F" /> <RowDefinition Height="Auto" SharedSizeGroup="G" /> </Grid.RowDefinitions> <Rectangle Fill="Green" Grid.Row="4" Height="10" HorizontalAlignment="Stretch" /> </Grid> <Grid x:Name="PART_MonthView" Grid.ColumnSpan="3" HorizontalAlignment="Center" Margin="6,-1,6,6" Grid.Row="1" Visibility="Visible"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" SharedSizeGroup="A" /> <RowDefinition Height="Auto" SharedSizeGroup="B" /> <RowDefinition Height="Auto" SharedSizeGroup="C" /> <RowDefinition Height="Auto" SharedSizeGroup="D" /> <RowDefinition Height="Auto" SharedSizeGroup="E" /> <RowDefinition Height="Auto" SharedSizeGroup="F" /> <RowDefinition Height="Auto" SharedSizeGroup="G" /> </Grid.RowDefinitions> </Grid> </Grid> <Grid x:Name="PART_YearView" Grid.ColumnSpan="3" HorizontalAlignment="Center" Margin="6,-3,7,6" Grid.Row="1" Visibility="Hidden"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> </Grid> </Grid> </Border> </Border> <Rectangle x:Name="PART_DisabledVisual" Fill="{StaticResource DisabledColor}" Opacity="0" RadiusX="2" RadiusY="2" Stroke="{StaticResource DisabledColor}" Stretch="Fill" StrokeThickness="1" Visibility="Collapsed" /> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Visibility" TargetName="PART_DisabledVisual" Value="Visible" /> </Trigger> <DataTrigger Binding="{Binding DisplayMode, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Calendar}}}" Value="Year"> <Setter Property="Visibility" TargetName="PART_MonthView0" Value="Hidden" /> <Setter Property="Visibility" TargetName="PART_YearView" Value="Visible" /> </DataTrigger> <DataTrigger Binding="{Binding DisplayMode, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Calendar}}}" Value="Decade"> <Setter Property="Visibility" TargetName="PART_MonthView0" Value="Hidden" /> <Setter Property="Visibility" TargetName="PART_YearView" Value="Visible" /> </DataTrigger> <DataTrigger Binding="{Binding Path=(local:CalendarHelper.ShowWeekNumber), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Calendar}}}" Value="true"> <Setter Property="Visibility" TargetName="PART_WeekNumber" Value="Visible" /> <Setter Property="Visibility" TargetName="br" Value="Visible" /> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <!-- DATEPICKER --> <Style TargetType="{x:Type DatePicker}"> <Setter Property="CalendarStyle" Value="{DynamicResource {x:Type Calendar}}" /> </Style> |
and usage like this (with the new style you can disable show week number)
1 2 3 4 5 6 7 8 9 10 11 12 |
<DatePicker HorizontalAlignment="Left" Height="29" VerticalAlignment="Top" Width="215" Margin="10,10,0,0" /> <Calendar HorizontalAlignment="Left" Margin="250,10,0,0" VerticalAlignment="Top" /> <Calendar HorizontalAlignment="Left" Margin="452,10,0,0" VerticalAlignment="Top" local:CalendarHelper.ShowWeekNumber="false" /> |
WARNING : for DatePicker is necessary to change style of CalendarItem for connect to dynamicresource of restyled style
CalendarStyle= »{DynamicResource {x:Type Calendar}} » or using redefine style of DatePicker
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!--#region Usage--> <DatePicker HorizontalAlignment="Left" Height="29" CalendarStyle="{DynamicResource {x:Type Calendar}}" VerticalAlignment="Top" Width="215" Margin="10,10,0,0" /> <!--#endregion--> or <!--#region redefine style of DatePicker--> <Style TargetType="{x:Type DatePicker}"> <Setter Property="CalendarStyle" Value="{DynamicResource {x:Type Calendar}}" /> </Style> <!--#endregion--> |
UPDATE : for getting first day of a week when clicking on week number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
public static class CalendarHelper { #region ShowWeekNumber public static bool GetShowWeekNumber(DependencyObject obj) => (bool)obj.GetValue(ShowWeekNumberProperty); public static void SetShowWeekNumber(DependencyObject obj, bool value) => obj.SetValue(ShowWeekNumberProperty, value); public static readonly DependencyProperty ShowWeekNumberProperty = DependencyProperty.RegisterAttached("ShowWeekNumber", typeof(bool), typeof(CalendarHelper), new PropertyMetadata(false , (ss, ee) => { if (ss is System.Windows.Controls.Calendar ca) { ca.Loaded += (s, e) => { // get grid with name var x = ca.FindChild<Grid>("PART_WeekNumber"); if (x != null) { EventHandler<CalendarDateChangedEventArgs> changed = (a, b) => { // get first day of month var dref = new DateTime(ca.DisplayDate.Year, ca.DisplayDate.Month, 1); // adjuste date if first days is monday if (dref.DayOfWeek == DayOfWeek.Monday) { dref = dref.AddDays(-1); } x.Children.Clear(); for (int row = 1; row <= 6; row++, dref = dref.AddDays(7)) { var tb = new TextBlock() { Text = GetWeekNumber(dref).ToString(), Background = Brushes.Transparent, Width = 12, TextAlignment = TextAlignment.Center, Tag = dref.Year, FontSize = 10, Margin = new Thickness(0, -2, 0, 0), VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, Foreground = Brushes.Gray, }; tb.MouseLeftButtonDown += (ss, ee) => { if (GetClickWeekCommand(ca) is ICommand ic) { if (ic.CanExecute(null)) { var date = GetFirstDayOfWeek( (int)tb.Tag, int.Parse(tb.Text) ); ic.Execute(date); } } }; Grid.SetRow(tb, row); x.Children.Add(tb); } }; ca.DisplayDateChanged += (sss, eee) => { changed(null, null); }; changed(null, null); } }; } })); #endregion #region ClickWeekCommand public static ICommand GetClickWeekCommand(DependencyObject obj) => (ICommand)obj.GetValue(ClickWeekCommandProperty); public static void SetClickWeekCommand(DependencyObject obj, int value) => obj.SetValue(ClickWeekCommandProperty, value); public static readonly DependencyProperty ClickWeekCommandProperty = DependencyProperty.RegisterAttached("ClickWeekCommand", typeof(ICommand), typeof(CalendarHelper), new PropertyMetadata(null //,(ss,ee) => { } )); #endregion #region Static methods public static int GetWeekNumber(DateTime from) { CultureInfo ciCurr = CultureInfo.CurrentCulture; return ciCurr.Calendar.GetWeekOfYear(from, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } public static T FindChild<T>(this DependencyObject parent, string childName) where T : DependencyObject { // Confirm parent and childName are valid. if (parent == null) return null; T foundChild = null; Debug.WriteLine($"ELEMENT TYPE = {parent.GetType()} -> {(parent as FrameworkElement).Name} #{VisualTreeHelper.GetChildrenCount(parent)}"); int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { var child = VisualTreeHelper.GetChild(parent, i); // If the child is not of the request child type child T childType = child as T; if (childType == null) { // recursively drill down the tree foundChild = FindChild<T>(child, childName); // If the child is found, break so we do not overwrite the found child. if (foundChild != null) break; } else if (!string.IsNullOrEmpty(childName)) { var frameworkElement = child as FrameworkElement; // If the child's name is set for search if (frameworkElement != null && frameworkElement.Name == childName) { // if the child's name is of the request name foundChild = (T)child; break; } else { // recursively drill down the tree foundChild = FindChild<T>(child, childName); // If the child is found, break so we do not overwrite the found child. if (foundChild != null) break; } } else { // child element found. foundChild = (T)child; break; } } return foundChild; } static DateTime GetFirstDayOfWeek(int year, int weekNumber) { DateTime jan1 = new DateTime(year, 1, 1); DateTime firstDayOfYear = jan1.AddDays(-((int)jan1.DayOfWeek - 1)); // Calculate the first Monday of the year int daysToAdd = (weekNumber - 1) * 7; DateTime result = firstDayOfYear.AddDays(daysToAdd); Debug.WriteLine($"First day of week {weekNumber} of year {year} is {result.ToShortDateString()}"); return result; } #endregion } |
if CalendarHelper.ClickWeekCommand is define you receive first day of week in command
like this
1 2 3 4 |
<Calendar HorizontalAlignment="Left" VerticalAlignment="Top" uchelper:CalendarHelper.ClickWeekCommand="{Binding ClickWeekCommand}" Margin="248,23,0,0" /> |
and using whith this command
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#region ClickWeek (COMMAND) RelayCommand _ClickWeekCommand; public ICommand ClickWeekCommand { get { if (_ClickWeekCommand == null) { _ClickWeekCommand = new RelayCommand(param => { if(param is DateTime dt) { Debug.WriteLine($"First day of week = {dt.ToShortDateString()}"); } }, param => true); } return _ClickWeekCommand; } } #endregion |
Commentaires récents