DateTimePicker.selectedDate is different from DateTimePicker.Text

I have a dateTimePicker. To write this DateTimePicker content to my database, I get the value with:

myDateTimePicker.selectedDate.value. 

This is normal when the user manually selects a date.

But ... when the user enters the date directly into DateTimePicker, SelectedDate.value gives me an older value. Good value is in the .Text property.

Is there a way to sync .Text with .SelectedValue.value ?

Maybe I need to read another property?

+4
source share
2 answers

This is because the check is only performed when the control loses focus. Typically, these controls are in dialog boxes (i.e. ShowDialog), and the dialog box is terminated by activating the OK button (directly or indirectly through the AcceptButton property). This causes the control to lose focus and test itself.

If you use DateTimePicker in a modeless window, you need to remove the focus from it before using its selected value so that it performs validation.

+1
source

You can use DateTimePicker from the extended WPF toolkit.

There is a Value property, and when you start typing the text field of this control, the entered value will be automatically assigned to your binding property.

Example:

XAML:

 <extToolkit:DateTimePicker Value="{Binding MyDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 

where "extToolkit":

 xmlns:extToolkit="http://schemas.xceed.com/wpf/xaml/toolkit" 

ViewModel Class:

 class MainViewModel : INotifyPropertyChanged { private DateTime _myDate; public DateTime MyDate { get { return _myDate; } set { _myDate = value; OnPropertyChanged("MyDate"); // only for testing... Console.WriteLine("value: " + value); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } 
0
source

Source: https://habr.com/ru/post/1469537/


All Articles