Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a DatePicker to display the date format day / month / year?

I'm using the Windows Phone 8.1 DatePicker

It's displaying the date as month/day/year by default and I can't see any way to change this to the 'correct' way of day/month/year.

This is how I declare the DatePicker

<DatePicker Name="datePicker" HorizontalAlignment="Center" MonthFormat="{}{month.full}"/>

displaying it as

enter image description here

I can see in the linked msdn article that I can use a DateTimeFormatter in conjunction with ComboBox selectors but that's not an option for me.

Is it possible?

like image 503
DaveDev Avatar asked Oct 17 '14 09:10

DaveDev


2 Answers

To Edit the Template

In Xaml every control has a style which you can manipulate, to change it's look and feel. Controls also inherit from one another, for example a date picker is made up of a button and a content container. And a button is made up of a border and a content container.

To Update the date pickers style.. Right click on the date picker control in visual studio from the Menu click edit template then click edit a copy. For this example you want to edit the style of the button template with in the date picker Template...

You will also need to create a Converter class to used in the template

This answer worked for me Page with date picker...

<Page
x:Class="DatePikerAnswer.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DatePikerAnswer"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
    <!-- Format Converter -->
    <local:DateConverter x:Key="FormatConverter"/>

    <!-- My Button Style-->
    <Thickness x:Key="PhoneBorderThickness">2.5</Thickness>
    <FontWeight x:Key="PhoneButtonFontWeight">Semibold</FontWeight>
    <x:Double x:Key="TextStyleLargeFontSize">18.14</x:Double>
    <x:Double x:Key="PhoneButtonMinHeight">57.5</x:Double>
    <x:Double x:Key="PhoneButtonMinWidth">109</x:Double>
    <Thickness x:Key="PhoneTouchTargetOverhang">0,9.5</Thickness>
    <SolidColorBrush x:Key="ButtonDisabledBackgroundThemeBrush" Color="Transparent"/>
    <Style x:Key="MyButtonStyle" TargetType="Button">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="BorderBrush" Value="{ThemeResource PhoneForegroundBrush}"/>
        <Setter Property="Foreground" Value="{ThemeResource PhoneForegroundBrush}"/>
        <Setter Property="BorderThickness" Value="{ThemeResource PhoneBorderThickness}"/>
        <Setter Property="FontFamily" Value="{ThemeResource PhoneFontFamilyNormal}"/>
        <Setter Property="FontWeight" Value="{ThemeResource PhoneButtonFontWeight}"/>
        <Setter Property="FontSize" Value="{ThemeResource TextStyleLargeFontSize}"/>
        <Setter Property="Padding" Value="9.5,0"/>
        <Setter Property="MinHeight" Value="{ThemeResource PhoneButtonMinHeight}"/>
        <Setter Property="MinWidth" Value="{ThemeResource PhoneButtonMinWidth}"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid x:Name="Grid" Background="Transparent">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition From="Pressed" To="PointerOver">
                                        <Storyboard>
                                            <PointerUpThemeAnimation Storyboard.TargetName="Grid"/>
                                        </Storyboard>
                                    </VisualTransition>
                                    <VisualTransition From="PointerOver" To="Normal">
                                        <Storyboard>
                                            <PointerUpThemeAnimation Storyboard.TargetName="Grid"/>
                                        </Storyboard>
                                    </VisualTransition>
                                    <VisualTransition From="Pressed" To="Normal">
                                        <Storyboard>
                                            <PointerUpThemeAnimation Storyboard.TargetName="Grid"/>
                                        </Storyboard>
                                    </VisualTransition>
                                </VisualStateGroup.Transitions>
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="PointerOver"/>
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <PointerDownThemeAnimation Storyboard.TargetName="Grid"/>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonPressedForegroundThemeBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="Border">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonPressedBackgroundThemeBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonDisabledForegroundThemeBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="Border">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonDisabledBorderThemeBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="Border">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonDisabledBackgroundThemeBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Margin="{ThemeResource PhoneTouchTargetOverhang}">
                            <ContentPresenter x:Name="ContentPresenter"
                                              AutomationProperties.AccessibilityView="Raw" 
                                              ContentTemplate="{TemplateBinding ContentTemplate}" 
                                              Content="{Binding Content,  RelativeSource={RelativeSource TemplatedParent},Converter={StaticResource FormatConverter},ConverterParameter=\{0:dd/MM/yyyy\}}" 
                                              Foreground="{TemplateBinding Foreground}" 
                                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                              Margin="{TemplateBinding Padding}" 
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!--DatePicker Style-->
    <FontFamily x:Key="PhoneFontFamilyNormal">Segoe WP</FontFamily>
    <x:Double x:Key="ContentControlFontSize">20.26</x:Double>
    <Style x:Key="MyDatePickerStyle1" TargetType="DatePicker">
        <Setter Property="FontFamily" Value="{ThemeResource PhoneFontFamilyNormal}"/>
        <Setter Property="FontSize" Value="{ThemeResource ContentControlFontSize}"/>
        <Setter Property="Foreground" Value="{ThemeResource DatePickerForegroundThemeBrush}"/>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="DatePicker">
                    <StackPanel x:Name="LayoutRoot" Margin="{TemplateBinding Padding}">
                        <ContentPresenter x:Name="HeaderContentPresenter"
                                          ContentTemplate="{TemplateBinding HeaderTemplate}"
                                          Content="{TemplateBinding Header}" Margin="0,0,0,-3" 
                                          Style="{StaticResource HeaderContentPresenterStyle}"/>
                        <Button x:Name="FlyoutButton" 
                                BorderBrush="{TemplateBinding Foreground}" 
                                BorderThickness="2.5" 
                                Background="{TemplateBinding Background}" 
                                Foreground="{TemplateBinding Foreground}" 
                                HorizontalAlignment="Stretch" 
                                HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                IsEnabled="{TemplateBinding IsEnabled}"
                                Style="{StaticResource MyButtonStyle}"
                                Padding="6.5,0,0,3"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>

 <Grid>

  </Grid>
</Page>

Converter Class ...

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;

namespace DatePikerAnswer
{
  class DateConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, string language)
    {
       if (value != null)
        {
            ///Convert Class throws exception so can not convert to date time
            string TheCurrentDate = value.ToString();

            string[] Values = TheCurrentDate.Split('/');
            string Day, Month, Year;

            Day = Values[1];
            Month = Values[0];
            Year = Values[2];

            string retvalue = string.Format("{0}/{1}/{2}", Day, Month, Year);
            return retvalue;
       }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
  }
}

The End Result is ...

enter image description here

like image 161
Stuart Smith Avatar answered Jan 02 '23 12:01

Stuart Smith


I needed to show Date as 'Month Year', I tried some solutions I thought about but they didn't work , searched a little and finally found this question and the answer by StuartSmith. Based on his answer I came up with similar solution that works around localization issue mentioned in comment by Kubaskista

@StuartSmith It will not work for German localization and probably some other regions due to different data format. btw: any idea why "value" in converter is not possible to convert into DateTime?

1- Define Date Picker in xaml, give it name "FirstDatePicker" and then from Designer edit template then choose edit a copy.

Date Picker Style

<DatePicker x:Name="FirstDatePicker" VerticalAlignment="Top" Grid.Row="1" Margin="0,12,0,0"    CalendarIdentifier="GregorianCalendar" DayVisible="False" Padding="0" Style="{StaticResource DatePickerStyle}" RequestedTheme="Light"/>

2- Right Click on FlyoutButton -> Additional Templates -> Edit Generated Content -> Edit a copy.

enter image description here

3- Inside content template, We will bind directly to Date property of FirstDatePicker and by using of StringFormatConverter you can format the date as you wish and override culture also.

<DataTemplate x:Key="DateFormatTemplate">
        <Grid>
            <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Date, ConverterParameter=MMMM yyyy, Converter={StaticResource DateFormatConverter}, ElementName=FirstDatePicker, Mode=OneWay}" VerticalAlignment="Top"/>
        </Grid>
    </DataTemplate>

4- Add StringFormatConverter to solution, Don't forget to add it to resources section of page.

  public class DateFormatConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert ( object value, Type targetType, object parameter, string language )
    {
        if(!(value is DateTime || value is DateTimeOffset) || parameter == null) return value;
        if(value is DateTime)
        {
            var date = (DateTime)value;
            return date.ToString(parameter.ToString(), CultureInfo.CurrentCulture);
        }
        else
        {
            var date = (DateTimeOffset)value;
            return date.ToString(parameter.ToString(), CultureInfo.CurrentCulture);
        }
    }

    public object ConvertBack ( object value, Type targetType, object parameter, string language )
    {
        throw new NotImplementedException();
    }

    #endregion
}

Note:You can change 'CultureInfo.CurrentCulture' to new Culture("ar-EG") as example or use language passed in converter.

Finally, Here is what i have in resources section of page

 <converters:DateFormatConverter x:Key="DateFormatConverter"/>
 <x:Double x:Key="ContentControlFontSize">20.26</x:Double>
    <FontWeight x:Key="PhoneButtonFontWeight2">Semibold</FontWeight>
    <DataTemplate x:Key="DateFormatTemplate">
        <Grid>
            <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Date, ConverterParameter=MMMM yyyy, Converter={StaticResource DateFormatConverter}, ElementName=FirstDatePicker, Mode=OneWay}" VerticalAlignment="Top"/>
        </Grid>
    </DataTemplate>
    <Style x:Key="DatePickerStyle" TargetType="DatePicker">
        <Setter Property="FontFamily" Value="{ThemeResource PhoneFontFamilyNormal}"/>
        <Setter Property="FontSize" Value="{ThemeResource ContentControlFontSize}"/>
        <Setter Property="Foreground" Value="{ThemeResource DatePickerForegroundThemeBrush}"/>
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="DatePicker">
                    <StackPanel x:Name="LayoutRoot" Margin="{TemplateBinding Padding}">
                        <ContentPresenter x:Name="HeaderContentPresenter" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Margin="0,0,0,-3" Style="{StaticResource HeaderContentPresenterStyle}"/>
                        <Button x:Name="FlyoutButton" BorderBrush="{TemplateBinding Foreground}" BorderThickness="2.5" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" HorizontalAlignment="Stretch" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsEnabled="{TemplateBinding IsEnabled}" Padding="12,10" Margin="0"   ContentTemplate="{StaticResource DateFormatTemplate}"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
like image 28
Ahmed Rashad Mohamed Avatar answered Jan 02 '23 13:01

Ahmed Rashad Mohamed