【问题标题】:How can I color the background of a date of WPF Calendar?如何为 WPF 日历的日期背景着色?
【发布时间】:2022-10-14 21:34:37
【问题描述】:

我正在做一个项目,目前遇到以下错误:每当我尝试为日期的背景着色时,它都不起作用。 XAML 示例有效,但是当我以编程方式尝试时,它显示错误。

这是 XAML 代码:

<Calendar x:Name="calendar">
    <Calendar.CalendarDayButtonStyle>
        <Style TargetType="CalendarDayButton">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Date}" Value="10/15/2022">
                    <Setter Property="Background" Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Calendar.CalendarDayButtonStyle>
</Calendar>

它确实显示了 15.10.2022 日期蓝色。

但是当我尝试以编程方式执行此操作时,我会这样做:

Dictionary<string, Color> dates = new Dictionary<string, Color>
{
    { "10/15/2022", Colors.Blue }
};

Style style = new Style(typeof(CalendarDayButton));

foreach (KeyValuePair<string, Color> item in dates)
{
    DataTrigger trigger = new DataTrigger()
    {
        Value = item.Key,
        Binding = new Binding("Date")
    };
    trigger.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(item.Value)));
    style.Triggers.Add(trigger);
}

calendar.CalendarDayButtonStyle = style;

它说: 'CalendarDayButton' TargetType 与元素 'CalendarButton' 的类型不匹配

以编程方式将其设置为 CalendarButton 对日历没有任何作用。

我怎样才能将它用作一种风格?

另外,有没有其他方法可以做到这一点?我一直试图让它工作几天但没有解决方案。我还尝试了其他一些 stackOverflow 主题,但有些来自旧版本的 .net 框架

我只是想让它看起来像这样(假设蓝色是背景)

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您必须设置StyleTargetType

    Style style = new Style()
    {
        TargetType = typeof(CalendarDayButton)
    };
    

    然后您的代码应该可以工作,即只需将Style style = new Style(typeof(CalendarDayButton)); 替换为上面的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2014-03-22
      相关资源
      最近更新 更多