WPF Datepicker text does not change to fit binding when user clears date

I have a datepicker in my window and want to achieve simple behavior: when the user clears the date of the datepicker text, set the datepicker to Today

XAML:

<DatePicker SelectedDate="{Binding DateFrom}" Width="150" Margin="0,20,0,0"></DatePicker>

      

ViewModel DateFrom property:

public DateTime? DateFrom
{
  get { return dateFrom; }
  set
  {
    if (dateFrom == value) return;
    dateFrom = value ?? DateTime.Today;
    OnPropertyChanged();
   }
}

      

But I run into strange behavior if the user cleared the date today from the datepicker - on the UI the datepicker remains empty, but in the ViewModel I have DateFrom == DateTime.Today

. If the user clears any other date, everything works as expected, only the script with the date Today fires.

Is this a dumper problem or am I missing something?

+3


source to share


2 answers


This should do the trick.

<DatePicker SelectedDate="{Binding DateFrom, UpdateSourceTrigger=LostFocus}"
  Width="150" Margin="0,20,0,0"></DatePicker>

      



The UpdateSourceTrigger

default is PropertyChanged

. But when you clear today's date, the property doesn't change.

So you have to change the value UpdateSourceTrigger

to LostFocus

. In this case, the property is updated every time it DatePicker

loses focus.

+1


source


Internally, it checks the previous and current values ​​and promotes the property that was changed only if it is different. I suppose it pickerAutomationPeer.RaiseValuePropertyChangedEvent(oldValue, newValue);

is if you dig the code OnSelectedDateChanged

inside the DatePicker.



The easiest way to avoid this is to make the values ​​always different by using DateTime.Now

instead DateTime.Today

.

+1


source







All Articles