2010-09-29 62 views
31

Necesito cambiar el formato de cadena de la DatePickerTextBox en el kit de herramientas de WPF DatePicker, a utilizar guiones en lugar de barras de los separadores.Cambiar el formato de cadena de la WPF DatePicker

¿Hay alguna manera de anular esta cultura predeterminada o el formato de cadena de visualización?

01-01-2010 

Respuesta

76

He resuelto este problema con una ayuda de este código. Espero que les ayude a todos también.

<Style TargetType="{x:Type DatePickerTextBox}"> 
<Setter Property="Control.Template"> 
    <Setter.Value> 
    <ControlTemplate> 
    <TextBox x:Name="PART_TextBox" 
    Text="{Binding Path=SelectedDate, StringFormat='dd MMM yyyy', 
    RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" /> 
    </ControlTemplate> 
    </Setter.Value> 
</Setter> 
</Style> 
+0

thx, me ayudó a resolver completamente el uso del selector de fecha para seleccionar solo el mes. Cité tu xaml en http://stackoverflow.com/questions/1798513/wpf-toolkit-datepicker-month-year-only/14902905#14902905. – GameAlchemist

+2

gran fan de este método. Prefiero hacer esto sobre cambiar la cultura. – Dom

+0

¡Esta es la verdadera respuesta! Actualmente, el truco sucio está marcado como la respuesta. Lástima. – dzendras

5

Lamentablemente, si usted está hablando de XAML, le pegan con el establecimiento de SelectedDateFormat a "largo" o "corto".

Si ha descargado la fuente de la Guía práctica junto con los binarios, se puede ver cómo se define. Éstos son algunos de los aspectos más destacados de ese código:

DatePicker.cs

#region SelectedDateFormat 

/// <summary> 
/// Gets or sets the format that is used to display the selected date. 
/// </summary> 
public DatePickerFormat SelectedDateFormat 
{ 
    get { return (DatePickerFormat)GetValue(SelectedDateFormatProperty); } 
    set { SetValue(SelectedDateFormatProperty, value); } 
} 

/// <summary> 
/// Identifies the SelectedDateFormat dependency property. 
/// </summary> 
public static readonly DependencyProperty SelectedDateFormatProperty = 
    DependencyProperty.Register(
    "SelectedDateFormat", 
    typeof(DatePickerFormat), 
    typeof(DatePicker), 
    new FrameworkPropertyMetadata(OnSelectedDateFormatChanged), 
    IsValidSelectedDateFormat); 

/// <summary> 
/// SelectedDateFormatProperty property changed handler. 
/// </summary> 
/// <param name="d">DatePicker that changed its SelectedDateFormat.</param> 
/// <param name="e">DependencyPropertyChangedEventArgs.</param> 
private static void OnSelectedDateFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
    DatePicker dp = d as DatePicker; 
    Debug.Assert(dp != null); 

    if (dp._textBox != null) 
    { 
     // Update DatePickerTextBox.Text 
     if (string.IsNullOrEmpty(dp._textBox.Text)) 
     { 
      dp.SetWaterMarkText(); 
     } 
     else 
     { 
      DateTime? date = dp.ParseText(dp._textBox.Text); 

      if (date != null) 
      { 
       dp.SetTextInternal(dp.DateTimeToString((DateTime)date)); 
      } 
     } 
    } 
} 



#endregion SelectedDateFormat 

private static bool IsValidSelectedDateFormat(object value) 
{ 
    DatePickerFormat format = (DatePickerFormat)value; 

    return format == DatePickerFormat.Long 
     || format == DatePickerFormat.Short; 
} 

private string DateTimeToString(DateTime d) 
{ 
    DateTimeFormatInfo dtfi = DateTimeHelper.GetCurrentDateFormat(); 

    switch (this.SelectedDateFormat) 
    { 
     case DatePickerFormat.Short: 
      { 
       return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.ShortDatePattern, dtfi)); 
      } 

     case DatePickerFormat.Long: 
      { 
       return string.Format(CultureInfo.CurrentCulture, d.ToString(dtfi.LongDatePattern, dtfi)); 
      } 
    }  

    return null; 
} 

DatePickerFormat.cs

public enum DatePickerFormat 
{ 
    /// <summary> 
    /// Specifies that the date should be displayed 
    /// using unabbreviated days of the week and month names. 
    /// </summary> 
    Long = 0, 

    /// <summary> 
    /// Specifies that the date should be displayed 
    ///using abbreviated days of the week and month names. 
    /// </summary> 
    Short = 1 
} 
20

Parece ser, según la respuesta de Wonko, que no se puede especificar el formato de fecha en formato Xaml o heredando el DatePicker.

He puesto el siguiente código en el constructor de mi punto de vista, que anula el ShortDateFormat para el subproceso actual:

CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name); 
ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"; 
Thread.CurrentThread.CurrentCulture = ci; 
9

El WPF Toolkit DateTimePicker ahora tiene un Format propiedad y una propiedad FormatString. Si especifica Custom como tipo de formato, puede proporcionar su propia cadena de formato.

<wpftk:DateTimePicker 
    Value="{Binding Path=StartTime, Mode=TwoWay}" 
    Format="Custom" 
    FormatString="MM/dd/yyyy hh:mmtt"/> 
1

clase Convertidor:

public class DateFormat : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value == null) return null; 
     return ((DateTime)value).ToString("dd-MMM-yyyy"); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

etiqueta de WPF

<DatePicker Grid.Column="3" SelectedDate="{Binding DateProperty, Converter={StaticResource DateFormat}}" Margin="5"/> 

creo que sirve

0

Formato exhibió dependiendo de la ubicación, pero esto se puede evitar al escribir esto:

! 10

Y serás feliz (dd '-' MM '-' yyy)

9

La respuesta aceptada (gracias @petrycol) me puso en el camino correcto, pero yo estaba recibiendo otra frontera cuadro de texto y color de fondo dentro del selector de fecha real. Se corrigió usando el siguiente código.

 <Style TargetType="{x:Type Control}" x:Key="DatePickerTextBoxStyle"> 
      <Setter Property="BorderThickness" Value="0"/> 
      <Setter Property="VerticalAlignment" Value="Center"/> 
      <Setter Property="Background" Value="{x:Null}"/> 
     </Style> 

     <Style TargetType="{x:Type DatePickerTextBox}" > 
      <Setter Property="Control.Template"> 
       <Setter.Value> 
        <ControlTemplate> 
         <TextBox x:Name="PART_TextBox" 
          Text="{Binding Path=SelectedDate, StringFormat='dd-MMM-yyyy', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" Style="{StaticResource DatePickerTextBoxStyle}" > 
         </TextBox> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
+0

¡Perfecto! trabajado como un encanto :-) – MaYaN

1

XAML

<DatePicker x:Name="datePicker" /> 

C#

var date = Convert.ToDateTime(datePicker.Text).ToString("yyyy/MM/dd"); 

poner lo que jamás formato que desee en ToString (""), por ejemplo ToString ("dd yyy MMM") y el formato de salida será 7 de junio de 2017

Cuestiones relacionadas