【问题标题】:How can I format a DatePicker to display the date format day / month / year?如何格式化 DatePicker 以显示日期格式日/月/年?
【发布时间】:2014-10-17 09:59:16
【问题描述】:

我使用的是 Windows Phone 8.1 DatePicker

默认将日期显示为 month/day/year,我看不出有任何方法可以将其更改为 day/month/year 的“正确”方式强>。

这就是我声明 DatePicker 的方式

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

显示为

我可以在链接的 msdn 文章中看到,我可以将 DateTimeFormatter 与 ComboBox 选择器结合使用,但这不是我的选择。

有可能吗?

【问题讨论】:

  • 投了反对票,没有评论....这个地方变成了reddit吗?这个问题有什么问题?
  • 大声笑不要试图理解投反对票的巨魔。只是不要眼神接触,它们就会消失。
  • 话虽如此,您是否尝试过编辑 DatePicker 模板?
  • 不,我该如何编辑模板?
  • @DaveDev 不确定您是否真的想弄乱文化信息设置。如果您想要 DD/MM/YYYY,请在 Package.appxmanifest 中将默认语言/文化从 en-US 更改。否则,您可能想看看System.Globalization.DateTimeFormatInfo.CurrentInfo 以及System.Globalization 的其余部分

标签: datepicker windows-runtime windows-phone windows-phone-8.1


【解决方案1】:

编辑模板

在 Xaml 中,每个控件都有一个样式,您可以操纵它来改变它的外观和感觉。控件也相互继承,例如日期选择器由按钮和内容容器组成。一个按钮由一个边框和一个内容容器组成。

要更新日期选择器样式.. 从菜单中右键单击 Visual Studio 中的日期选择器控件单击编辑模板,然后单击编辑副本。对于此示例,您想在日期选择器模板中编辑按钮模板的样式...

您还需要创建一个 Converter 类以在模板中使用

这个答案对我有用 带有日期选择器的页面...

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

转换器类 ...

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();
    }
  }
}

最终结果是……

【讨论】:

  • 感谢您的全面回答!我会在星期一早上试一试,然后告诉你我是怎么做的。
  • 我试了一下 - 它看起来不错,但是当您点击日期时,它会抛出 ArgumentException 并显示消息“参数不正确。放置目标需要在可视化树中。”我不知道如何解决它!
  • 经过进一步调查,这个错误似乎不是您的代码的错 - 这是我的应用程序中的一个错误!操……
  • 很高兴我能帮上忙。
  • @StuartSmith 由​​于数据格式不同,它不适用于德语本地化,并且可能不适用于其他一些地区。顺便说一句:知道为什么转换器中的“值”无法转换为 DateTime?
【解决方案2】:

我需要将 Date 显示为“Month Year”,我尝试了一些我想过的解决方案,但没有奏效,搜索了一下,最后找到了这个问题和 StuartSmith 的答案。 根据他的回答,我想出了类似的解决方案,可以解决 Kubaskista 评论中提到的本地化问题

@StuartSmith 由​​于数据格式不同,它不适用于德语本地化,可能还有其他一些地区。顺便说一句:知道为什么转换器中的“值”无法转换为 DateTime 吗?

1- 在 xaml 中定义日期选择器,将其命名为“FirstDatePicker”,然后从 Designer 编辑模板中选择编辑副本。

<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- 右键单击​​ FlyoutButton -> 附加模板 -> 编辑生成的内容 -> 编辑副本。

3- 在内容模板中,我们将直接绑定到 FirstDatePicker 的 Date 属性,通过使用 StringFormatConverter 您可以根据需要格式化日期并覆盖文化。

<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- 将 StringFormatConverter 添加到解决方案中,不要忘记将其添加到页面的资源部分。

  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
}

注意:您可以将 'CultureInfo.CurrentCulture' 更改为 new Culture("ar-EG") 作为示例或使用转换器中传递的语言。

最后,这是我在页面资源部分的内容

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    相关资源
    最近更新 更多