using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Windows;
using
System.Windows.Controls;
using
System.Windows.Data;
using
System.Windows.Documents;
using
System.Windows.Input;
using
System.Windows.Media;
using
System.Windows.Media.Imaging;
using
System.Windows.Shapes;
namespace
WpfApplication2
{
/// <summary>
/// Interaction logic for ValidationTest.xaml
/// </summary>
public
partial
class
ValidationTest : Window
{
public
ValidationTest()
{
InitializeComponent();
SimpleCustomer c =
new
SimpleCustomer();
c.Name =
"Fred"
;
c.Address =
"1/3 Powell Street"
;
this
.DataContext = c;
}
}
/// <summary>
/// 异常验证
/// </summary>
public
class
SimpleCustomer
{
public
SimpleCustomer()
{ }
private
string
m_strName;
public
string
Name
{
set
{
this
.m_strName = value;
if
(String.IsNullOrEmpty(
this
.m_strName))
{
throw
new
ApplicationException(
"Customer name is mandatory."
);
}
}
get
{
return
this
.m_strName;
}
}
private
string
m_strAddress;
public
string
Address
{
set
{
this
.m_strAddress = value;
}
get
{
return
this
.m_strAddress;
}
}
}
/// <summary>
/// 自定义验证
/// </summary>
public
class
StringRangeValidationRule : ValidationRule
{
public
StringRangeValidationRule()
{ }
private
int
m_intMinimumLength = -1;
public
int
MinimumLength
{
set
{
this
.m_intMinimumLength = value;
}
get
{
return
this
.m_intMinimumLength;
}
}
private
int
m_intMaximumLength = -1;
public
int
MaximumLength
{
set
{
this
.m_intMaximumLength = value;
}
get
{
return
this
.m_intMaximumLength;
}
}
private
string
m_strErrorMessage =
string
.Empty;
public
string
ErrorMessage
{
set
{
this
.m_strErrorMessage = value;
}
get
{
return
this
.m_strErrorMessage;
}
}
public
override
ValidationResult Validate(
object
value, System.Globalization.CultureInfo cultureInfo)
{
ValidationResult result =
new
ValidationResult(
true
,
null
);
string
inputString =(value ??
string
.Empty).ToString();
if
( inputString ==
null
)
{
inputString =
string
.Empty;
}
if
(inputString.Length <
this
.m_intMinimumLength || inputString.Length >
this
.m_intMaximumLength)
{
return
new
ValidationResult(
false
,
this
.ErrorMessage);
}
return
result;
}
}
}