WPF中的日期验证. [英] Date validation in WPF.
本文介绍了WPF中的日期验证.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想验证以dd/mm/yyyy格式输入的日期.使用exceptionvalidation,仅当日期以mm/dd/yyyy格式输入时,我才能正确验证.有人可以建议一些解决方法吗?
I want to validate the date entered in the format dd/mm/yyyy. Using exceptionvalidation I can validate correctly only if the date is entered in the format mm/dd/yyyy. Can anyone suggest some workarounds?
推荐答案
什么是"exceptionvalidation"?那是一堂课吗?一项技术?您是否尝试过使用正则表达式进行验证?这是有关如何执行此操作的文章: WPF中的正则表达式验证
What is "exceptionvalidation"? Is that a class? A technique? Have you tried validating with a regular expression? Here is an article on how to do that: Regex Validation in WPF
您尝试过IDataErrorInfo接口吗?
http://www.abhisheksur.com/2010/06/validate-your-application- using.html [^ ]
Did you try IDataErrorInfo interfacE ?
http://www.abhisheksur.com/2010/06/validate-your-application-using.html[^]
以下是我解决它的方法.谁能告诉我做同一件事的正确方法是什么?这似乎是个坏主意.
The following is the way i solved it. Can anyone tell me whats the correct way to go about doing the same thing? This just seems like bad idea..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
namespace Demo
{
class DateDemo
{
private DateTime? _date=null;
public DateTime? Date
{
get {
return this._date;
}
set
{
this._date = (DateTime)value;
}
}
}
class CheckDate : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
try
{
//CultureInfo culture = CultureInfo.CreateSpecificCulture("en-AU");
Convert.ToDateTime(value.ToString());
return new ValidationResult(true, "Valid Date");
}
catch
{
return new ValidationResult(false, "Invalid Date");
}
}
}
class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null) return System.Convert.ToDateTime(value);
else return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
int day; int month; int year;
string date = value.ToString();
try
{
int.TryParse(date.Substring(0, 2), out day);
int.TryParse(date.Substring(3, 2), out month);
int.TryParse(date.Substring(6, 4), out year);
return new DateTime(year, month, day);
}
catch
{
return new Exception("Please Enter Date in DD/MM/YYYY format");
}
}
else
{
throw new Exception("Please Enter Date in DD/MM/YYYY format");
}
}
}
}
<TextBox Name="txtDate" DataContext="{Binding}">
<TextBox.Text>
<Binding Path="Date" StringFormat="{}{0:dd/MM/yyyy}" TargetNullValue="Please enter the date in DD/MM/YYYY format" Converter="{StaticResource converter}" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<local:CheckDate />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox
>
>
这篇关于WPF中的日期验证.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文