问题
Simplified Question:
I have a datepicker in WPF. I enter a value 30/10/1983 in the textbox of the datepicker. I need the value to be posted back to my viewmodel, where in I have bound it to a DateTime? property.
Is there any way I can achieve this. mm/dd/yyyy format triggers a postback but not dd/mm/yyyy.
The DatePicker code is as below.
<DatePicker Grid.Row="2" Name="inputDate"
Text="{Binding BirthDate,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
>
</DatePicker>
The view model property is as below.
private DateTime? birthDate;
public DateTime? BirthDate
{
get
{
return this.birthDate;
}
set
{
this.birthDate = value;
OnPropertyChanged("BirthDate");
}
}
I enter a value 10/10 into the datepicker textbox, the setter gets called with a value, but the moment I enter an entire date 30/10/1983, I still have the view model property which is equal to NULL.
I have changed the Format to English-UnitedKingdom, in the calendar settings, and my CurrentCulture reflects en-GB appropriately.
Original Question:
I have a datetimepicker control in WPF, which I have bound the text property to a Nullable DateTime in the view model.
The problem I am facing is when I enter a value in the format MM/dd/yyyy, I do get a value postback in the view model, indicating the new value.
But when I enter the value in dd/MM/yyyy format, I do not get a notification in the view model and the value is lost. The bound propertyin the view model is null.
The short date format is the one which I have specified in the calendar settings & dateFormat, within which for a short date format I provide the entry as "dd/MM/yyyy".
Could someone please help me with this scenario where in I accept date in dd/MM/yyyy format, and I do not want to hardcode, I wish to pick up the short date format from the calendar settings and also, I wish to recieve the updated value in the view model too.
回答1:
The problem is related that a not valid date will not set with a correct value your ViewModel DateTime property. So, you can intercept it and convert correctly with a CONVERTER.
An example:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string strValue = System.Convert.ToString(value);
DateTime resultDateTime;
if (DateTime.TryParse(strValue, out resultDateTime))
{
return resultDateTime;
}
return value;
}
And your XAML code will be like:
<DatePicker
Text="{Binding BirthDate,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedDate="{Binding RelativeSource={RelativeSource Self},Path=Text,
Converter={StaticResource DateConverter}}"
/>
来源:https://stackoverflow.com/questions/26843658/datepicker-wpf-accepting-dd-mm-yyyy-format