在Calendar控件中更改某些假日日期的背景

时间:2015-12-26 07:59:59

标签: c# mysql wpf calendar

我在wpf桌面应用程序中使用基本日历控件,我的要求是使用c#语言从常规日期区分假日(来自mysql数据库的日期)。我的代码就像:

<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)
        {
            listboxSelectedDates.Items.Clear();
            foreach (DateTime dr in MyCalendar.SelectedDates)
            {
                listboxSelectedDates.Items.Add(dr.ToShortDateString());
            }//add selected dates in list

          MySqlConnection conn = new MySqlConnection("Server=localhost;database=newcompanydatabase;pwd=Admin@123;uid=root;");
            string q = "select _date from event_calendar;";
            MySqlCommand cmd = new MySqlCommand(q,conn);
            conn.Open();
            MySqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                if(MyCalendar.SelectedDate==rdr.GetDateTime(0))
                {
                    MessageBox.Show("******* holiday");                    

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

        }

如何使用c#更改假期的颜色?

2 个答案:

答案 0 :(得分:1)

我们可以为每个假期创建一个DataTrigger

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

但由于假日日期存储在数据库中,因此我们需要在循环中使用代码添加DataTrigger

  1. 定义Style定位CalenderDayButton

    <Style x:Key="cdbKey" TargetType="CalendarDayButton">
    ...                         
    </Style>
    
  2. 设置CalendarDayButtonStyle属性

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

  3. 在适当的位置(窗口构造函数等)从DB获取您的假期日期。

    List<DateTime> holidaysDates = _getHolidayDatesFromDB();
    
  4. 使用C#代码在步骤3中收到的假日日期列表循环添加DataTriggers,并将其添加到上面定义的Style

            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));
              s.Triggers.Add(dataTrigger);
            /*End Loop*/
    

    我们在Binding("Date")中使用Binding作为我们的DataTrigger属性值,这是因为CalenderDayButtonDataContext自动设置为DateTime } value。

  5. 我已将Background的{​​{1}}更改为SandyBrown,您可以获得更高级的效果。

答案 1 :(得分:0)

有几种方法可以实现您的目标,但我会专注于一个特定的解决方案。

<强>概念

我们将定义一个辅助类,它将具有两个附加的依赖属性,我们稍后将其附加到代表Calendar控件中特定日期的控件。这些将是Date - 标识控件所代表的日期,IsHoliday - 只读属性,指示日期(由Date标识)是否为假日。然后我们会在每个控件上设置一个触发器,只要该控件的IsHolidaytrue,它就会改变背景。

<强>实施

首先,帮助类:

namespace MyHelpers
{
    public class HolidayHelper
    {
        public static DateTime GetDate(DependencyObject obj)
        {
            return (DateTime)obj.GetValue(DateProperty);
        }

        public static void SetDate(DependencyObject obj, DateTime value)
        {
            obj.SetValue(DateProperty, value);
        }

        public static readonly DependencyProperty DateProperty =
        DependencyProperty.RegisterAttached("Date", typeof(DateTime), typeof(HolidayHelper), new PropertyMetadata { PropertyChangedCallback = DatePropertyChanged });

        private static void DatePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var date = GetDate(d);
            SetIsHoliday(d, CheckIsHoliday(date));
        }

        private static bool CheckIsHoliday(DateTime date)
        {
            //here we should determine whether 'date' is a holiday
            //or not and return corresponding value
        }

        private static readonly DependencyPropertyKey IsHolidayPropertyKey =
        DependencyProperty.RegisterAttachedReadOnly("IsHoliday", typeof(bool), typeof(HolidayHelper), new PropertyMetadata());

        public static readonly DependencyProperty IsHolidayProperty = IsHolidayPropertyKey.DependencyProperty;

        public static bool GetIsHoliday(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsHolidayProperty);
        }

        private static void SetIsHoliday(DependencyObject obj, bool value)
        {
            obj.SetValue(IsHolidayPropertyKey, value);
        }
    }
}

每当Date属性附加到任何DependencyObject或其值发生更改时,IsHoliday属性都会相应更新。

现在有一些有用的事实:

  • Calendar控件中的每个日期都由CalendarDayButton控件
  • 显示
  • 对于每个CalendarDayButton控件,相应的日期存储在其DataContext属性
  • 可以使用CalendarDayButton属性
  • 为特定Calendar自定义Calendar.CalendarDayButtonStyle控件

我们需要做的是将HolidayHelper.Date属性绑定到CalendarDayButton.DataContext,并在HolidayHelper.IsHoliday上设置触发器以更新CalendarDayButton.Background

<Calendar xmlns:helpers="clr-namespace:MyHelpers">
    <Calendar.CalendarDayButtonStyle>
        <Style TargetType="{x:Type CalendarDayButton}">
            <Setter Property="helpers:HolidayHelper.Date" Value="{Binding}" />
            <Style.Triggers>
                <Trigger Property="helpers:HolidayHelper.IsHoliday" Value="True">
                    <Setter Property="Background" Value="..." />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Calendar.CalendarDayButtonStyle>
</Calendar>