Home > Blockchain >  WPF DatePicker Custom Format
WPF DatePicker Custom Format

Time:12-21

As mentioned I am looking to customize the datepicker dates to YYYY-MM-DD I have in my XAML file:

<DatePicker x:Name="DatePicker_Date"  Width="300px" VerticalAlignment="Center" HorizontalAlignment="Center" >
                    <DatePicker.Resources>
                        <Style TargetType="{x:Type DatePickerTextBox}">
                            <Setter Property="Control.Template">
                                <Setter.Value>
                                    <ControlTemplate>
                                        <TextBox x:Name="PART_TextBox"
                                 Text="{Binding Path=SelectedDate, 
                                        RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, 
                                        StringFormat={x:Static local:App.DateFormat}}" />
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </DatePicker.Resources>
                </DatePicker>

And then in my App.xaml.cs file I have:

 public partial class App : Application
{
    public static string DateFormat = "yyyy-MM-dd";
}

So this works to display the date the proper way within the picker itself but when I go to reference that date :

string dateTemp = DatePicker_Date.Text;

It just prints out the original date format MM-DD-YYYY

What am I missing here -- I can't use PART_Textbox.text that isn't working. How can I get that newly formatted text into a string?

I have followed a few of these solutions on stack overflow but they seem to have same result, the one I like best is set in app.xaml resources so I don't have to do it everytime for each date picker within my application but I have same issue:

 <Style TargetType="{x:Type DatePickerTextBox}">
 <Setter Property="VerticalContentAlignment" Value="Center"/>
 <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>

Relatively new to WPF apologies for my ignorance.

CodePudding user response:

You should get the currently selected date as a DateTime using the SelectedDate property and then format it according to your specific format:

string dateTemp = DatePicker_Date.SelectedDate?.ToString(App.DateFormat);
  • Related