C# WPF,日期选择器验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30075720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# WPF, Datepicker validation
提问by Tomas Bruckner
I'm trying to validate date in XAML using validation rules.
我正在尝试使用验证规则验证 XAML 中的日期。
<StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal">
<DatePicker Height="25" x:Name="DatePickerDate">
<DatePicker.SelectedDate>
<Binding Path="ViewModel.Date" NotifyOnValidationError="True">
<Binding.ValidationRules>
<validationRules:DatePickerValidationRule/>
</Binding.ValidationRules>
</Binding>
</DatePicker.SelectedDate>
</DatePicker>
</StackPanel>
And Validation rule
和验证规则
public class DatePickerValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
var date = (DateTime) value;
return date.Date.CompareTo(DateTime.Now) < 0
? new ValidationResult(false, "the date can not be before today")
: new ValidationResult(true, null);
}
}
But when I put breakpoint into validation rule, it never goes there even if I change the Date.
但是当我将断点放入验证规则时,即使我更改了日期,它也永远不会到达那里。
Since I am new to WPF, it would be appreciable if any suggestions or guidance are available here.
由于我是 WPF 的新手,如果这里有任何建议或指导,我将不胜感激。
Thanks.
谢谢。
回答by xanth
Had the same problem and thought I should share my solution:
有同样的问题,并认为我应该分享我的解决方案:
I had a static minimum date constraint so just specified BlackoutDates
我有一个静态的最小日期限制,所以只指定了 BlackoutDates
<DatePicker SelectedDate="{Binding StartDate}" Name="DepartureDate">
<DatePicker.BlackoutDates>
<CalendarDateRange Start="1/1/0001" End="12/31/1969"/>
</DatePicker.BlackoutDates>
</DatePicker>
But if you need a more dynamic solution you could consider this solution.
但是如果你需要一个更动态的解决方案,你可以考虑这个解决方案。
回答by Evgeny Sobolev
Inside your Save() function
在您的 Save() 函数中
this.DatePickerDate.SelectedDate = this.DatePickerDate.SelectedDate;
This should force the validation rule to validate
这应该强制验证规则进行验证

