简体   繁体   中英

Turn invalid date into standard default date “01/01/1900” wpf datepicker c#

If I write in WPF datepicker "Feb 30,2018" or "14/9/2018" or any invalid date it should convert into standard default date "01/01/1900" and if possible also give messgaebox "Invalid date". My Code of XML is :

 <DatePicker x:Name="DatePicker1" SelectedDateFormat="Short" Margin="10,10,10,0" Grid.ColumnSpan="5" 
                    IsTodayHighlighted="True"  RenderTransformOrigin="0.129,-2.84" PreviewTextInput="DatePicker1_PreviewTextInput" 
                    DateValidationError="DatePicker1_DateValidationError" 
                    DisplayDateStart="1/1/1990"  SelectedDate="{x:Static sys:DateTime.Now}"  LostFocus="DatePicker1_LostFocus" Height="28" VerticalAlignment="Top" CalendarOpened="DatePicker1_CalendarOpened" >
                    <DatePicker.Resources>
                        <Style TargetType="{x:Type DatePickerTextBox}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate>
                                        <TextBox x:Name="PART_TextBox"
                                            Text="{Binding SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, StringFormat=dd-MMM-yyyy}" />
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </DatePicker.Resources>
                </DatePicker>

attached output of my Datepicker 在此处输入图片说明

if i write invalid date then it should populate messagebox and set as default date "01/01/1900".

How about if you go by the msdn recommendation and use

SelectedDate="{Binding Day, TargetNullValue={x:Static system:DateTime.Now}}"

https://social.msdn.microsoft.com/Forums/vstudio/en-US/7db00560-633e-42cc-b49b-a755ac3e6e59/default-date-in-datepicker?forum=wpf

And if you want 01/01/1990 you swap the latter to a binding of your own or DateTime.MinValue if you're after the effect to show that it's not a proper date?

As for feedback to the user you could perhaps go with something like

SelectedDate="{Binding Day, FallbackValue={x:Static sys:DateTime.Today}}"

^ means that if the binding fails for any reason (invalid date for instance), it should fall back to whatever you set the binding to. In this case DateTime.Today.

Perhaps you can solve the information back to the user by putting a label next to the DateTime which is visible when the date is invalid? Or play around with the HintText of the DateTime component?

Hopefully this is the type of solution you're after!

You have a LostFocus event handler: DatePicker1_LostFocus

You can add your validation logic in the event handler:

private void DatePicker1_LostFocus(object sender, RoutedEventArgs e)
{
    if (e.OriginalSource is TextBox textBox)
    {
        var val = textBox.Text;

        if(!DateTime.TryParse(val, out var dateTimeVal))
        {
            MessageBox.Show($"The entered value ({val}) is not valid.");
            textBox.Text = new DateTime(1900, 1, 1).ToShortDateString();
        }
    }
}
  • The above code gets the user entered text value
  • Validates whether it is valid value
  • If validation fails, it shows the message and resets the value

For invalid date:

在此处输入图片说明

After reset:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM