Reputation: 1578
I have datepicker on my window and want to achieve simple behaviour: when user clear datepicker's text set datepicker date 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 encounter weird behaviour if user clear today date from datepicker - on UI datepicker stays empty, but in ViewModel I have DateFrom == DateTime.Today
. If user clear any other date all works as expected, only scenario with Today Date fails.
Is this datepicker issue or I'm missing something?
Upvotes: 3
Views: 2018
Reputation:
That should do the trick.
<DatePicker SelectedDate="{Binding DateFrom, UpdateSourceTrigger=LostFocus}"
Width="150" Margin="0,20,0,0"></DatePicker>
The value of UpdateSourceTrigger
is PropertyChanged
by default. But when you clear today's date, the property is not changing.
So, you have to change the value of UpdateSourceTrigger
to LostFocus
. In that case the property is updated every time DatePicker
loses focus.
Upvotes: 1
Reputation: 4774
Internally it checks previous and current values, and raises property changed only if they are different. I suppose it's pickerAutomationPeer.RaiseValuePropertyChangedEvent(oldValue, newValue);
if you dig into OnSelectedDateChanged
code inside DatePicker.
The easiest way to avoid that is to make values always different by using DateTime.Now
instead of DateTime.Today
.
Upvotes: 1