从WPF DatePicker,日历禁用周末

时间:2015-03-04 09:07:11

标签: c# wpf xaml datepicker

我在wpf应用程序中有一个简单的日期选择器。我希望从日历中删除所有周末。 为此,我使用了DatePicker的BlackoutDates属性。

我的代码如下(MVVM架构):

这是在XAML

<DatePicker Name="MyDatePicker">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="CalendarOpened">
               <Commands:EventToCommand Command="{Binding DataContext.CalenderOpenedCmd,
               RelativeSource={RelativeSource AncestorType={x:Type Window}, Mode=FindAncestor}}" 
               CommandParameter="{Binding ElementName=MyDatePicker}"/>
        </i:EventTrigger>
   </i:Interaction.Triggers>
</DatePicker>

然后在MainWindowViewModel.cs

public ICommand CalenderOpenedCmd { get; set; }
CalenderOpenedCmd = new DelegateCommand(ExecuteMyDatePicker_RemoveSaturdays);

ExecuteMyDatePicker_RemoveSaturdays就是这个事件。

private void ExecuteMyDatePicker_RemoveSaturdays(object obj)
{
    var datePicker = obj as DatePicker;
    if (datePicker == null)
        return;
    datePicker.DisplayDateStart = new DateTime(1995, 1, 1);

    // In following 2 variables I'm deciding the range for BlackoutDates property.
    var minDate = datePicker.DisplayDateStart ?? DateTime.MinValue;  
    var maxDate = DateTime.Today;

   // In the following for loop, I'm checking every date in given range and if the day is Saturday or Sunday I'm adding them to blackoutdates to remove them form the calender.
    for (var day = minDate; day <= maxDate && DateTime.MaxValue > day; day = day.AddDays(1))
    {
        if (day.DayOfWeek == DayOfWeek.Saturday || day.DayOfWeek == DayOfWeek.Sunday)
        {
            datePicker.BlackoutDates.Add(new CalendarDateRange(day));
        }
    }
}

如果日期范围为30 - 40年,则上述代码需要花费太多时间才能执行。因此,我想知道如何优化此代码或任何其他方式从WPF的整个日期选择器中删除所有周末,无论我提供的日期范围如何。

0 个答案:

没有答案