you can try the following solution.
First create the following converter :
public class StringToDateTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return null;
}
return ((DateTime)value).ToString(parameter as string, CultureInfo.InvariantCulture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (string.IsNullOrEmpty(value as string))
{
return null;
}
try
{
DateTime dt = DateTime.ParseExact(value as string, parameter as string, CultureInfo.InvariantCulture);
return dt as DateTime?;
}
catch (Exception)
{
return null;
}
}
}
Then in the xaml, you will have to create an instance of the converter and use it in the textbox of the DatePicker
<Window x:Class="TestDatePicker.MainWindow"
...
xmlns:converters="clr-namespace:TestDatePicker"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
...
<converters:StringToDateTimeConverter x:Key="StringToDateTimeConverter" />
</Window.Resources>
<Grid DataContext="{StaticResource MainWindowVM}">
...
<DatePicker Height="25" HorizontalAlignment="Left" Margin="5,36,0,0" Name="dtpStartDate"
SelectedDate="{Binding StartDateSelectedDate}" VerticalAlignment="Top" Width="115">
<DatePicker.Resources>
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox"
Text="{Binding Path=SelectedDate, RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}, Converter={StaticResource StringToDateTimeConverter}, ConverterParameter=yyyy/MM/dd}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DatePicker.Resources>
</DatePicker>
...
</Grid>
Finally, in the viewmodel, the property must be of type DateTime? (i.e a nullable DateTime).
private DateTime? _startDateSelectedDate;
public DateTime? StartDateSelectedDate
{
get { return _startDateSelectedDate; }
set
{
if (_startDateSelectedDate != value)
{
_startDateSelectedDate = value;
RaisePropertyChanged(() => this.StartDateSelectedDate);
}
}
}
I hope this will help you
Regards
Claude
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…