Changing the string format of the WPF DatePicker

前端 未结 9 1732
广开言路
广开言路 2020-11-27 14:56

I need to change the string format of the DatePickerTextBox in the WPF Toolkit DatePicker, to use hyphens instead of slashes for the seperators.

Is there a way to ov

相关标签:
9条回答
  • 2020-11-27 15:37

    As Ben Pearce answered we can use the CultureInfo Class to take care of the Custom Format, I really think is the only logical way. And if you have different dateTimePickers which have different Format, you can use:

    CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
    ci.DateTimeFormat.LongDatePattern = "MMM.yyyy"; //This can be used for one type of DatePicker
    ci.DateTimeFormat.ShortDatePattern = "dd.MMM.yyyy"; //for the second type
    Thread.CurrentThread.CurrentCulture = ci;
    

    And then you can just change the DateFormat in the .xaml document.

      <DatePicker Name="dateTimePicker1" SelectedDateFormat="Long"  />
    
    0 讨论(0)
  • 2020-11-27 15:38

    I have solved this problem with a help of this code. Hope it will help you all as well.

    <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 讨论(0)
  • 2020-11-27 15:45

    It appears, as per Wonko's answer, that you cannot specify the Date format in Xaml format or by inheriting from the DatePicker.

    I have put the following code into my View's constructor which overrides the ShortDateFormat for the current thread:

    CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
    ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
    Thread.CurrentThread.CurrentCulture = ci;
    
    0 讨论(0)
提交回复
热议问题