I have a viewmodel that contains a pair of DateTime? objects – nullable DateTimes.
private DateTime? _xmitdtFrom;
public DateTime? xmitdtFrom
{
get { return this._xmitdtFrom; }
set
{
this._xmitdtFrom = value;
notifyPropertyChanged("xmitdtFrom");
}
}
private DateTime? _xmitdtTo;
public DateTime? xmitdtTo
{
get { return this._xmitdtTo; }
set
{
this._xmitdtTo = value;
notifyPropertyChanged("xmitdtTo");
}
}
The xmitdtFrom date cannot be greater than the xmitdtFrom date, the xmitdtTo date cannot be before the xmitdtFrom date, and neither the xmitdtTo date not the xmitdtFrom can be after today.
So, in the markup I have this:
<Label Grid.Row="1" Grid.Column="1">
From:
</Label>
<DatePicker Grid.Row="1" Grid.Column="2"
SelectedDate="{Binding xmitdtFrom, Mode=TwoWay}"
DisplayDateEnd="{Binding xmitdtTo}"
/>
<Label Grid.Row="2" Grid.Column="1">
Through:
</Label>
<DatePicker Grid.Row="2" Grid.Column="2"
SelectedDate="{Binding xmitdtTo, Mode=TwoWay}"
DisplayDateStart="{Binding xmitdtFrom}"
DisplayDateEnd="{x:Static sys:DateTime.Now}"
/>
And this works fine, unless xmitdtTo is null – in which case xmitdtFrom is unrestricted, which is a problem.
What I want is to set DisplayDateEnd for the xmitdtFrom to the xmitdtTo, if it’s not null, or to DateTime.Now, if it is.
And I’m wondering what might be the cleanest way of accomplishing this.
I decided to go with another approach entirely.
Instead of messing about with the viewmodel, I created an IfNullConverter, that when used in a binding would pass the bound object, if it was not null, or would pass its ConversionParameter, if it was.
And I used that in binding the from date’s DisplayDateEnd – with xmitDTTo as the bound property, and DateTime.Now as the ConversionParameter.
Solves the problem cleanly, entirely within the UI (and this is a UI problem, not a data problem, so I’d prefer a solution that doesn’t pollute the viewmodel). And it creates a general purpose functionality, that will be available to use in other similar circumstances.
The converter:
The binding: