I have a datapicker in wpf and I have to disable past dates. I am using a MVVM p开发者_运维技巧attern. Is it possible?
How do you do it?
You can use the DisplayDateStart
and DisplayDateEnd
properties of DatePicker
. They are dependencies properties so you can supply them via your DataContext
using MVVM. Here's the documentation:
- DatePicker.DisplayDateStart Property
- DatePicker.DisplayDateEnd Property
Additional to Rick's answer, the DisplayDateStart and DisplayDateEnd only affect the calendar, it does not stop the user from typeing a valid date outside this range.
To do this you could throw an exception in the setter in the bound property in your ViewModel or if you are using IDataErrorInfo, return a validation error message via this[string columnName]
ExceptionValidationRule:
<Binding Path="SelectedDate" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
You have to set the DisplayDateStart
attribute with Today's date
<DatePicker Name="dt_StartDateFrom" DisplayDateStart="{x:Static sys:DateTime.Today}">
</DatePicker>
Make sure you have set the
xmlns:sys="clr-namespace:System;assembly=mscorlib"
in your <UserControl>
tag to be able to use the sys:
parameter
P.S. To Disable future dates, you can use DisplayDateEnd
attribute
This could be a neater solution if your disabled date ranges involve constants that you want keep in xaml.
If you are using MVVM we can appy custom attributes to do the validation.
public Class MyModel : INotifyPropertyChanged{
private DateTime _MyDate;
[FutureDateValidation(ErrorMessage="My Date should not be greater than current Date")]
public DateTime Mydate{
get{return _MyDate;}
set{
_Mydate=value;
}
}
}
The implementation for the FutureDateValidation will be given as follows
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
class FutureDateValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
ErrorMessage = ErrorMessageString;
DateTime inputDateTime = (DateTime)value;
if (inputDateTime != null)
{
if (inputDateTime > DateTime.Now)
{
return new ValidationResult(ErrorMessage);
}
else {
return null;
}
}
else {
return null;
}
}
}
精彩评论