-1

In my wpf application, i have used DatePicker control. I am having issue with the format of DatePicker control. It doesn't take the form as i specified, instead of that it is taking the default system format. I have set the datetime format in my application startup file like below,

 string currentCulture = AppSettings.Locale;
        CultureInfo ci = new System.Globalization.CultureInfo(currentCulture);
        ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        Thread.CurrentThread.CurrentUICulture = ci;

in xaml i have set ma selected date like below

SelectedDate="{Binding DateOfBirth, StringFormat='DD/MM/YYYY', Mode=TwoWay}"

in style i have set the text like below

Text="{Binding Path=SelectedDate, StringFormat='dd/MM/yyyy', 
                            RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}">

What else i have missed ? why the format is not getting changed?Can anyone help me on this?

PS: I recently updated to .net framework version 4.7

mm8
  • 163,881
  • 10
  • 57
  • 88
user3610920
  • 1,582
  • 2
  • 13
  • 24
  • take a look here: https://stackoverflow.com/q/4041197/5605739 – Celso Lívero Feb 27 '18 at 13:44
  • I usually use in my MainWindows.xaml `` [Language](https://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.language(v=vs.110).aspx) (I'm brazilian), so I do not need to format the date as ´dd/mm/yyyy´ – Celso Lívero Feb 27 '18 at 14:06

2 Answers2

0

Try this:

<DatePicker SelectedDate="{Binding DateOfBirth}">
    <DatePicker.Resources>
        <Style TargetType="{x:Type DatePickerTextBox}">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <TextBox x:Name="PART_TextBox"
                                 Text="{Binding Path=SelectedDate, StringFormat='dd/MM/yyyy', 
                                 RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DatePicker.Resources>
</DatePicker>
mm8
  • 163,881
  • 10
  • 57
  • 88
  • I have used same as like the one you suggested in ma style. the format is okay while am selecting, but when the datepicker last focus the date format will get changed based on system focus. – user3610920 Feb 28 '18 at 05:42
0

The problem get resolved if i add the following line in ma startup file

Thread.CurrentThread.CurrentCulture = ci;

So The culture part should look like below:

string currentCulture = AppSettings.Locale;
        CultureInfo ci = new System.Globalization.CultureInfo(currentCulture);
        ci.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        Thread.CurrentThread.CurrentUICulture = ci;
        Thread.CurrentThread.CurrentCulture = ci;
user3610920
  • 1,582
  • 2
  • 13
  • 24