Reputation: 16040
I have a datapicker in wpf and I have to disable past dates. I am using a MVVM pattern. Is it possible?
How do you do it?
Upvotes: 4
Views: 6384
Reputation: 35
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;
}
}
}
Upvotes: 0
Reputation: 1198
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
Upvotes: 2
Reputation: 606
This could be a neater solution if your disabled date ranges involve constants that you want keep in xaml.
Upvotes: 0
Reputation: 38333
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>
Upvotes: 3
Reputation: 34240
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:
Upvotes: 8