2010-09-29 20 views
31

È necessario modificare il formato stringa di DatePickerTextBox in WPF Toolkit DatePicker, per utilizzare i trattini anziché le barre per i separatori.Modifica del formato stringa di WPF DatePicker

C'è un modo per sovrascrivere questa cultura predefinita o il formato di stringa di visualizzazione?

01-01-2010 

risposta

76

ho risolto questo problema con l'aiuto di questo codice. Spero che ti aiuterà anche a tutti.

<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, mi ha aiutato a risolvere completamente l'utilizzo del selettore di data per selezionare solo il mese. Ho citato il tuo xaml in http://stackoverflow.com/questions/1798513/wpf-toolkit-datepicker-month-year-only/14902905#14902905. – GameAlchemist

+2

Grande fan di questo metodo. Preferisco farlo cambiando la cultura. – Dom

+0

Questa è la vera risposta! Attualmente, il trucco sporco è contrassegnato come la risposta. Pietà. – dzendras

5

Purtroppo, se si parla di XAML, si è bloccato con l'impostazione SelectedDateFormat a "lungo" o "corto".

Se si è scaricato il sorgente del Toolkit insieme ai file binari, è possibile vedere come viene definito. Ecco alcuni dei punti salienti di tale codice:

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

Sembra, secondo la risposta di Wonko, che non è possibile specificare il formato Data in formato Xaml o ereditato da DatePicker.

ho messo il seguente codice nel costruttore del mio punto di vista, che sostituisce lo ShortDateFormat per il thread corrente:

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

Il WPF Toolkit DateTimePicker ora ha una proprietà e una proprietà FormatFormatString. Se si specifica Custom come tipo di formato, è possibile fornire la propria stringa di formato.

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

classe Converter:

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

tag WPF

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

Speranza che aiuta

0

Formato esibivano a seconda della posizione, ma questo può essere evitato scrivendo questo:

! 10

E sarete felici (dd '-' MM '-' yyy)

9

La risposta accettata (grazie @petrycol) mi ha messo sulla strada giusta, ma mi è stato sempre un altro confine casella di testo e colore di sfondo all'interno della selezione data effettiva. Risolto usando il seguente codice.

 <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

Perfetto! ha funzionato come un fascino :-) – MaYaN

1

XAML

<DatePicker x:Name="datePicker" /> 

C#

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

messo che cosa mai formattare che si desidera in ToString (""), ad esempio ToString ("dd MMM yyy") e il formato di output sarà 7 giu 2017

Problemi correlati