Change Background Of Some Holiday Dates In Calendar Control

- 1 answer

I am using a basic calendar control in wpf desktop app and my requirement is to differentiate holidays (dates which are coming from mysql database) from regular dates by using c# language. My code is like :

<Calendar Name="MyCalendar"  Grid.Column="1" Grid.Row="3" Grid.ColumnSpan="3" Grid.RowSpan="6"   Foreground="Aqua" SelectionMode="MultipleRange" SelectedDatesChanged="MyCalendar_SelectedDatesChanged" ></Calendar>

C# :

 private void MyCalendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
            foreach (DateTime dr in MyCalendar.SelectedDates)
            }//add selected dates in list

          MySqlConnection conn = new MySqlConnection("Server=localhost;database=newcompanydatabase;[email protected];uid=root;");
            string q = "select _date from event_calendar;";
            MySqlCommand cmd = new MySqlCommand(q,conn);
            MySqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
                    MessageBox.Show("******* holiday");                    

            }//if selected date is holiday, show occasion.


How can I change back color of holidays using c#?



We can create one DataTrigger for every holiday.

<Style x:Key="cdbKey" TargetType="CalendarDayButton">
          <DataTrigger Binding="{Binding Date}" Value="12/07/2015">
              <Setter Property="Background" Value="Turquoise"/>
          ... more such DataTriggers for every holiday

But as holiday dates are stored in the database, so we need to add DataTrigger using code in a loop.

  1. Define a Style targetting CalenderDayButton.

    <Style x:Key="cdbKey" TargetType="CalendarDayButton">
  2. Set CalendarDayButtonStyle property

    <Calendar ... CalendarDayButtonStyle="{StaticResource cdbKey}">

  3. Get your holiday dates from DB at proper place (window constructor etc).

    List<DateTime> holidaysDates = _getHolidayDatesFromDB();
  4. Add DataTriggers using a loop for holiday dates list received in Step 3, using C# code and add them to the Style defined above.

            Style s = (Style)this.Resources["cdbKey"];
            /* Loop through the Dates retrieved from DataBase*/
              DateTime holidayDate = DateTime.Parse("10/02/2015");
              DataTrigger dataTrigger = new DataTrigger() { Binding = new Binding("Date"), Value = holidayDate };
              dataTrigger.Setters.Add(new Setter(CalendarDayButton.BackgroundProperty, Brushes.SandyBrown));
            /*End Loop*/

    We have used Binding("Date") as our Binding property value in DataTrigger, this is because CalenderDayButton is having DataContext set automatically to a DateTime value.

I have changed Background of CalenderDayButton to SandyBrown, you can get fancier.