在WPF日历上记下特定日期

时间:2019-07-08 05:37:30

标签: c# wpf

我正在尝试在WPF日历控件上标记数据库源中的特定日期。

这是代码段。

XAML

<Style x:Key="calendarDayButtonStyle" TargetType="CalendarDayButton">
<Calendar Name="CalendarSelectDate" />

.cs代码。

var dateList = GetDatesFromDB();
Style dayButtonStyle = (Style)this.Resources["calendarDayButtonStyle"];
foreach (DateObject date in dateList)
{
  var DataTrigger dataTrigger = new DataTrigger() { Binding = new Binding("Date"), Value = new DateTime(date.Year, date.Month, date.Day) }; // 
  dataTrigger.Setters.Add(new Setter(FontWeightProperty, FontWeights.Bold));
  dayButtonStyle.Triggers.Add(dataTrigger);  // This will throw TriggerCollection -exception.
}
calendarDayButtonStyle.CalendarDayButtonStyle = dayButtonStyle;  // this will sealed TriggerCollection.

此代码在初始运行时有效。

但是,如果再次在运行时事件上运行它,说如果我将新日期添加到数据库中,然后再次运行代码,它将抛出After a 'TriggerCollection' is in use (sealed), it cannot be modified.错误。

我了解的是,将样式分配给日历后,TriggerCollection被密封了。

是否有更好的方法在WPF日历上动态标记日期?

1 个答案:

答案 0 :(得分:1)

每次创建一个新的Style。您可以基于BasedOn属性在XAML中定义的那一个:

var dateList = GetDatesFromDB();
Style dayButtonStyle = new Style() { BasedOn = (Style)this.Resources["calendarDayButtonStyle"] };
foreach (DateObject date in dateList)
{
    var dataTrigger = new DataTrigger() { Binding = new Binding("Date"), Value = new DateTime(date.Year, date.Month, date.Day) };
    dataTrigger.Setters.Add(new Setter(FontWeightProperty, FontWeights.Bold));
    dayButtonStyle.Triggers.Add(dataTrigger);
}
dayButtonStyle.Seal();
calendarDayButtonStyle.CalendarDayButtonStyle = dayButtonStyle;