Home > Enterprise >  How can I color the background of a date of WPF Calendar?
How can I color the background of a date of WPF Calendar?

Time:10-18

I am working on a project and I am currently stuck on the following error: Whenever I try to color the background of a date, it doesn't work. The XAML example works but when I try it programatically, it shows an error.

Here is the XAML code:

<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>

It does show the 15.10.2022 date blue.

But when I try to do it programatically, I do it like this:

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;

It says that: 'CalendarDayButton' TargetType does not match type of element 'CalendarButton'"

Setting it to CalendarButton programmatically does nothing to the calendar.

How can I use it as a style?

Also, is there any other way to do so? I kept trying to make it work for a few days yet no solution. I also tried some other stackOverflow topics but some are from old versions of .net frame

I just want it to look like this (pretend that the blue color is a background)

CodePudding user response:

You must set the TargetType of the Style:

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

Then your code should work, i.e. just replace Style style = new Style(typeof(CalendarDayButton)); with the code above.

  • Related