Few days ago I got a requirement to show calendar for ticket booking app in windows but there is no default control to show calendar in windows phone. So i need to create custom control to achieve this task and also love to share it with you. Let’s start your Visual Studio, create a new Windows Phone app and paste these code snippets in you Xaml page.
Now paste the C# code to show the monthly calendar like below.
C# code - using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Runtime.InteropServices.WindowsRuntime;
- using Windows.Foundation;
- using Windows.Foundation.Collections;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- using Windows.UI.Xaml.Controls.Primitives;
- using Windows.UI.Xaml.Data;
- using Windows.UI.Xaml.Input;
- using Windows.UI.Xaml.Media;
- using Windows.UI.Xaml.Navigation;
-
- namespace CalendarDemo
- {
-
-
-
- public sealed partial class MainPage: Page
- {
- DateTime calendarDate;
- public MainPage()
- {
- this.InitializeComponent();
- calendarDate = DateTime.Today;
- this.NavigationCacheMode = NavigationCacheMode.Required;
- }
-
-
-
-
-
- protected override void OnNavigatedTo(NavigationEventArgs e)
- {
- UpdateCalendar(calendarDate);
- }
- public void UpdateCalendar(DateTime objdate)
- {
- CalendarHeader.Text = objdate.ToString("MMMM yyyy");
- objdate = new DateTime(objdate.Year, objdate.Month, 1);
- int dayOfWeek = (int) objdate.DayOfWeek + 1;
- int daysOfMonth = DateTime.DaysInMonth(objdate.Year, objdate.Month);
- int i = 1;
- foreach(var o1 in Calendar.Children)
- {
- foreach(var o2 in (o1 as StackPanel).Children)
- {
- var o3 = (o2 as Grid).Children[0] as TextBlock;
- if (i >= dayOfWeek && i < (daysOfMonth + dayOfWeek))
- {
- o3.Text = (i - dayOfWeek + 1).ToString();
- }
- else
- {
- o3.Text = "";
- }
- i++;
- }
- }
- }
- private void previousMonth(object sender, RoutedEventArgs e)
- {
- calendarDate = calendarDate.AddMonths(-1);
- UpdateCalendar(calendarDate);
- }
- private void nextMonth(object sender, RoutedEventArgs e)
- {
- calendarDate = calendarDate.AddMonths(1);
- UpdateCalendar(calendarDate);
- }
- }
- }
The calendar is linked to a Universal
DateTime object which is used to track the actual Month/ Year, I used to make it Universal and in this way it will make it easier to switch to the next or previous month. It looks simpler just like this.
Now run the app and show the output as in the following screenshot: