Search code examples
wpfcalendarstring-formatting

Change WPF Calendar control day name format


I am currently using WPF Calendar control. The Day names are displayed as Su, Mo, Tu, etc. But I want those to be displayed as Sun, Mon, Tue, etc.. I found there is no data template property to achieve this one.

Any suggestion will be greatly appreciated.

Thanks


Solution

  • I've looked into this and unfortunately, I don't think that you will be able to achieve what you want.

    To start with, I found the StringFormat to show three character day names in the Custom Date and Time Format Strings page at MSDN:

    StringFormat=ddd
    

    Then I thought that you might find a solution for the rest of your problem in the Custom date format for WPF Calendar CalendarItems post. So, adapting the idea from @Quartermeister, I could tried the following:

    <Calendar>
        <Calendar.CalendarButtonStyle>
            <Style TargetType="primitives:CalendarButton">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="primitives:CalendarButton">
                            <primitives:CalendarButton>
                                <TextBlock Text="{Binding Day, StringFormat=ddd}"/>
                            </primitives:CalendarButton>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Calendar.CalendarButtonStyle>
    </Calendar>
    

    As you can imagine, I was way off because this answered a different problem. So I went back to MSDN to find the default ControlTemplate for the Calendar control to experiment further. If you look at that ControlTemplate, you will see a Style named CalendarItemStyle.

    In that Style is a ControlTemplate and in its Resources section, you will see a DataTemplate with the key {x:Static CalendarItem.DayTitleTemplateResourceKey}. Finally, in that DataTemplate, you will see the TextBlock that is responsible for displaying the day names:

    <TextBlock Foreground="#FF333333"
                       FontWeight="Bold"
                       FontSize="9.5"
                       FontFamily="Verdana"
                       Margin="0,6,0,6"
                       Text="{Binding}"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center" />
    

    I increased the size of the day names, so we can be sure that that is the correct TextBlock. (Ignore the odd looking Buttons at the top - they are just like that because I didn't copy their ControlTemplates):

    enter image description here

    Now if you look at the Binding in that TextBlock, you will see that unfortunately, it is set to {Binding}. This means that it is using the whole data bound value, rather than setting a particular StringFormat on a DateTime object. This means that we cannot use a StringFormat because the data bound value is already a string.