WPF自己喜欢用的数据验证方式

粘一个自己实践的例子

第一步:定义验证模型。

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace DecorationMS.WindowsBase
{
class DMSValidatiionRule
{
private const string emailPatten = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";
private const string phonePatten = @"^\d{11}$";
private const string nullablePhonePatten = @"^\w{0}$|^\d{11}$";
private const string NOPatten = @"^\d+$";
private const string fullChar = @"^[\u0000-\u00FF]*$";//半角
//验证规则
private string notEmty;
private string mobilePhone;
private string phoneNO;
private string number;
//
public string NotEmty
{
get { return this.notEmty; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ApplicationException("* 不能为空");
}

else
{
this.notEmty = value;
}
}
}
public string Number
{
get { return this.number; }
set
{

if (!Regex.IsMatch(value, fullChar) || !Regex.IsMatch(value, NOPatten))
{
throw new ApplicationException(" * 需纯数字");
}

else
{
this.number = value;
}

}
}
public string MobilePhone
{
get { return this.mobilePhone; }
set
{

if (!Regex.IsMatch(value, fullChar)||!Regex.IsMatch(value,phonePatten))
{
throw new ApplicationException("* 请输入11位半角纯数字");
}

else
{
this.mobilePhone = value;
}

}
}
public string PhoneNO
{
get { return this.phoneNO; }
set
{
if (!Regex.IsMatch(value, fullChar) || !Regex.IsMatch(value, nullablePhonePatten))
{
throw new ApplicationException("* 请输入11位半角纯数字或留空");
}

else
{
this.phoneNO = value;
}

}
}
}
}

第二步:将验证模型引用到窗口的静态资源中

1. xmlns:DecorationMS="clr-namespace:DecorationMS.WindowsBase" 

2.  <DecorationMS:DMSValidatiionRule x:Key="dmsValiations"/> 

第三步:将文本框的值绑定到静态资源,并要求验证规则

 <TextBox.Text>
<Binding Source="{StaticResource dmsValiations}" Path="NotEmty">
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
至次,已次实现了基本的数据验证,接下来进一步完善
第四步,做个模板来显示错误提示
<ControlTemplate x:Key="errorTemp">
<DockPanel>
<AdornedElementPlaceholder Name="MyAdorner"/>
<TextBlock Foreground="Red" Text="{Binding ElementName=MyAdorner,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
</TextBlock>
</DockPanel>
</ControlTemplate>
第五步,给TextBox绑定模板,并将验效时机从失焦改为字符改变时动态验证
 1.Validation.ErrorTemplate="{StaticResource errorTemp}
2.NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged"
致此XAML完整的代码如下:
<DecorationMS:DMSbase x:Class="DecorationMS.InfoAddWindows.AddPartnerWindow"
xmlns:DecorationMS
="clr-namespace:DecorationMS.WindowsBase"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>

<DecorationMS:DMSValidatiionRule x:Key="dmsValiations"/>
<ControlTemplate x:Key="errorTemp">
<DockPanel>
<AdornedElementPlaceholder Name="MyAdorner"/>
<TextBlock Foreground="Red" Text="{Binding ElementName=MyAdorner,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
</TextBlock>
</DockPanel>
</ControlTemplate>
</Window.Resources>

<TextBox Name="tbName" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center"
Validation.ErrorTemplate
="{StaticResource errorTemp}">
<TextBox.Text>
<Binding Source="{StaticResource dmsValiations}" Path="NotEmty" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>

</TextBox.Text>

第六步,在提交时再验证一次
BindingExpression evenName = this.tbName.GetBindingExpression(TextBox.TextProperty);

if (evenName.HasError)
{ MessageBox.Show(evenName.ValidationError.ErrorContent.ToString()); }

现在应该是全都完成,但再给一点建议:在窗口加载时设置一个reset程序,用以立即“激活”验证规则(textbox的值改变过了),否则会。。。。自己试试吧


原文地址:https://www.cnblogs.com/Laro/p/1986852.html