在做表单的,需要对User提交数据做验证,wpf与silverlight 都提供自带的验证机制,但是只是验证,并不能在提交时提供详细的信息,此时可使用 依赖属性将错误信息整合进自定义错误集合中,即可在提交时获取相应错误信息方便后续业务处理。

Silverlifgt版本:

public class ValidationScope
{
public FrameworkElement ScopeElement { get; private set; } private readonly ObservableCollection<ValidationError> _errors = new ObservableCollection<ValidationError>(); public ObservableCollection<ValidationError> Errors
{
get { return _errors; }
} public bool IsValid()
{
return _errors.Count == 0;
} public static string GetValidateBoundProperty(DependencyObject obj)
{
return (string)obj.GetValue(ValidateBoundPropertyProperty);
} public static void SetValidateBoundProperty(DependencyObject obj, string value)
{
obj.SetValue(ValidateBoundPropertyProperty, value);
} public static readonly DependencyProperty ValidateBoundPropertyProperty =
DependencyProperty.RegisterAttached("ValidateBoundProperty", typeof(string), typeof(ValidationScope), new PropertyMetadata(null)); public static ValidationScope GetValidationScope(DependencyObject obj)
{
return (ValidationScope)obj.GetValue(ValidationScopeProperty);
} public static void SetValidationScope(DependencyObject obj, ValidationScope value)
{
obj.SetValue(ValidationScopeProperty, value);
} public static readonly DependencyProperty ValidationScopeProperty =
DependencyProperty.RegisterAttached("ValidationScope", typeof(ValidationScope), typeof(ValidationScope), new PropertyMetadata(null, ValidationScopeChanged)); private static void ValidationScopeChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
{
ValidationScope oldScope = args.OldValue as ValidationScope;
if (oldScope != null)
{
oldScope.ScopeElement.BindingValidationError -= oldScope.ScopeElement_BindingValidationError;
oldScope.ScopeElement = null;
} FrameworkElement scopeElement = source as FrameworkElement;
if (scopeElement == null)
{
throw new ArgumentException(string.Format(
"'{0}' is not a valid type.ValidationScope attached property can only be specified on types inheriting from FrameworkElement.",
source));
} ValidationScope newScope = (ValidationScope)args.NewValue;
newScope.ScopeElement = scopeElement;
newScope.ScopeElement.BindingValidationError += newScope.ScopeElement_BindingValidationError;
} private void ScopeElement_BindingValidationError(object sender, ValidationErrorEventArgs e)
{
if (e.Action == ValidationErrorEventAction.Removed)
{
Errors.Remove(e.Error);
}
else if (e.Action == ValidationErrorEventAction.Added)
{
Errors.Add(e.Error);
}
} public void ValidateScope()
{
ForEachElement(ScopeElement, delegate(DependencyObject obj)
{
string propertyName = GetValidateBoundProperty(obj);
if (!string.IsNullOrEmpty(propertyName))
{
FrameworkElement element = (FrameworkElement)obj;
var field = element.GetType().GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public)
.Where(p => p.FieldType == typeof(DependencyProperty) && p.Name == (propertyName + "Property"))
.FirstOrDefault(); if (field == null)
{
throw new ArgumentException(string.Format(
"Dependency property '{0}' could not be found on type '{1}'; ValidationScope.ValidateBoundProperty",
propertyName, element.GetType()));
}
var be = element.GetBindingExpression((DependencyProperty)field.GetValue(null));
be.UpdateSource();
}
});
} private static void ForEachElement(DependencyObject root, Action<DependencyObject> action)
{
int childCount = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < childCount; i++)
{
var obj = VisualTreeHelper.GetChild(root, i);
action(obj);
ForEachElement(obj, action);
}
}
}

  WPF版:

 public class ValidationScope
{
public FrameworkElement ScopeElement { get; private set; } private readonly ObservableCollection<ValidationError> _errors = new ObservableCollection<ValidationError>(); public ObservableCollection<ValidationError> Errors
{
get { return _errors; }
} public bool IsValid()
{
return _errors.Count == 0;
} public static string GetValidateBoundProperty(DependencyObject obj)
{
return (string)obj.GetValue(ValidateBoundPropertyProperty);
} public static void SetValidateBoundProperty(DependencyObject obj, string value)
{
obj.SetValue(ValidateBoundPropertyProperty, value);
} public static readonly DependencyProperty ValidateBoundPropertyProperty =
DependencyProperty.RegisterAttached("ValidateBoundProperty", typeof(string), typeof(ValidationScope), new PropertyMetadata(null)); public static ValidationScope GetValidationScope(DependencyObject obj)
{
return (ValidationScope)obj.GetValue(ValidationScopeProperty);
} public static void SetValidationScope(DependencyObject obj, ValidationScope value)
{
obj.SetValue(ValidationScopeProperty, value);
} public static readonly DependencyProperty ValidationScopeProperty =
DependencyProperty.RegisterAttached("ValidationScope", typeof(ValidationScope), typeof(ValidationScope), new PropertyMetadata(null, ValidationScopeChanged)); private static void ValidationScopeChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
{
ValidationScope oldScope = args.OldValue as ValidationScope;
if (oldScope != null)
{
oldScope.ScopeElement.RemoveHandler(System.Windows.Controls.Validation.ErrorEvent, new RoutedEventHandler(oldScope.ScopeElement_BindingValidationError));
oldScope.ScopeElement = null;
} FrameworkElement scopeElement = source as FrameworkElement;
if (scopeElement == null)
{
throw new ArgumentException(string.Format(
"'{0}' is not a valid type.ValidationScope attached property can only be specified on types inheriting from FrameworkElement.",
source));
} ValidationScope newScope = (ValidationScope)args.NewValue;
newScope.ScopeElement = scopeElement;
newScope.ScopeElement.AddHandler(System.Windows.Controls.Validation.ErrorEvent, new RoutedEventHandler(newScope.ScopeElement_BindingValidationError), true);
} public void ScopeElement_BindingValidationError(object sender, RoutedEventArgs e)
{
System.Windows.Controls.ValidationErrorEventArgs args = e as System.Windows.Controls.ValidationErrorEventArgs; if (args.Error.RuleInError is System.Windows.Controls.ValidationRule)
{
BindingExpression bindingExpression = args.Error.BindingInError as System.Windows.Data.BindingExpression; string propertyName = bindingExpression.ParentBinding.Path.Path;
DependencyObject OriginalSource = args.OriginalSource as DependencyObject; string errorMessage = "";
ReadOnlyObservableCollection<System.Windows.Controls.ValidationError> errors = System.Windows.Controls.Validation.GetErrors(OriginalSource);
if (errors.Count > 0)
{
StringBuilder builder = new StringBuilder();
builder.Append(propertyName).Append(":");
System.Windows.Controls.ValidationError error = errors[errors.Count - 1];
{
if (error.Exception == null || error.Exception.InnerException == null)
builder.Append(error.ErrorContent.ToString());
else
builder.Append(error.Exception.InnerException.Message);
}
errorMessage = builder.ToString();
} StringBuilder errorID = new StringBuilder();
errorID.Append(args.Error.RuleInError.ToString());
if (args.Action == ValidationErrorEventAction.Added)
{
Errors.Add(args.Error);
}
else if (args.Action == ValidationErrorEventAction.Removed)
{
Errors.Remove(args.Error);
} }
} public void ValidateScope()
{
ForEachElement(ScopeElement, delegate(DependencyObject obj)
{
string propertyName = GetValidateBoundProperty(obj);
if (!string.IsNullOrEmpty(propertyName))
{
FrameworkElement element = (FrameworkElement)obj;
var field = element.GetType().GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public)
.Where(p => p.FieldType == typeof(DependencyProperty) && p.Name == (propertyName + "Property"))
.FirstOrDefault(); if (field == null)
{
throw new ArgumentException(string.Format(
"Dependency property '{0}' could not be found on type '{1}'; ValidationScope.ValidateBoundProperty",
propertyName, element.GetType()));
}
var be = element.GetBindingExpression((DependencyProperty)field.GetValue(null));
be.UpdateSource();
}
});
} private static void ForEachElement(DependencyObject root, Action<DependencyObject> action)
{
int childCount = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < childCount; i++)
{
var obj = VisualTreeHelper.GetChild(root, i);
action(obj);
ForEachElement(obj, action);
}
}
}

  

wpf表单验证的更多相关文章

  1. WPF权限控制——【3】数据库、自定义弹窗、表单验证

    你相信"物竞天择,适者生存"这样的学说吗?但是我们今天却在提倡"尊老爱幼,救死扶伤",帮助并救护弱势群体:第二次世界大战期间,希特勒认为自己是优等民族,劣势民族 ...

  2. 利刃 MVVMLight 5:绑定在表单验证上的应用

    表单验证是MVVM体系中的重要一块.而绑定除了推动 Model-View-ViewModel (MVVM) 模式松散耦合 逻辑.数据 和 UI定义 的关系之外,还为业务数据验证方案提供强大而灵活的支持 ...

  3. C# WPF 表单更改提示

    微信公众号:Dotnet9,网站:Dotnet9,问题或建议,请网站留言: 如果您觉得Dotnet9对您有帮助,欢迎赞赏 C# WPF 表单更改提示 内容目录 实现效果 业务场景 编码实现 本文参考 ...

  4. jQuery学习之路(8)- 表单验证插件-Validation

    ▓▓▓▓▓▓ 大致介绍 jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求.该插件捆绑了一套有用的验证方法,包括 ...

  5. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  6. form表单验证-Javascript

    Form表单验证: js基础考试内容,form表单验证,正则表达式,blur事件,自动获取数组,以及css布局样式,动态清除等.完整代码如下: <!DOCTYPE html PUBLIC &qu ...

  7. ASP.NET MVC5+EF6+EasyUI 后台管理系统(33)-MVC 表单验证

    系列目录 注:本节阅读需要有MVC 自定义验证的基础,否则比较吃力 一直以来表单的验证都是不可或缺的,微软的东西还是做得比较人性化的,从webform到MVC,都做到了双向验证 单单的用js实现的前端 ...

  8. 实现跨浏览器html5表单验证

    div:nth-of-type(odd){ float: left; clear: left; } .origin-effect > div:nth-of-type(even){ float: ...

  9. jQuery Validate 表单验证 — 用户注册简单应用

    相信很多coder在表单验证这块都是自己写验证规则的,今天我们用jQuery Validate这款前端验证利器来写一个简单的应用. 可以先把我写的这个小demo运行试下,先睹为快.猛戳链接--> ...

随机推荐

  1. Diskpart手动创建EFI、MSR引导分区

    当给电脑加新硬盘时候,并且需要把新硬盘当作系统盘,有几种方法来为新硬盘创建引导分区: 可以选择用U盘刻录微软原版系统镜像,直接从U盘启动,然后直接创建分区,直接装,会自动为硬盘创建好几个引导分区. 进 ...

  2. JAXB--obj2xml&xml2obj

    参考: https://www.cnblogs.com/mumuxinfei/p/8948299.html  去掉 xsi:type="echoBody" xmlns:xsi=&q ...

  3. configure: error: no acceptable C compiler found in $PATH 解决

    在安装keepalived时报错 ./configure --prefix=/usr/local/ccbase/keepalived-2.0.15 && make && ...

  4. tomcat在win10系统中安装失败的问题,修改tomcat内存

    自己以前在其他系统上安装tomcat服务都没有问题,但是在win10系统上安装就经常出现问题,自己总结了一下安装步骤: 1.首先需要配置环境变量, CATALINA_HOME 2.修改service. ...

  5. javaWeb核心技术之分页和条件

    分页:limit ?,? 参数1 : startIndex 开始索引. 参数2 : pageSize 每页显示的个数 n 表示第几页 给定一个特殊的单词 pageNumber select * fro ...

  6. 截取字符,超出的用省略号代替js实现 substring

    可用到截取文字过多的问题,取0到6之间的字符,不包含6title.substring(0,6)+'...';

  7. ISR吞吐性能问题

    ISR大致可以分几类: Cisco 860.880.890 ISR1800 (fixed).1800 (modular).2800.3800 Series ISR1900.2900.3800.3900 ...

  8. angular 输入框自动绑定值最长为16位,超过16位则会报错

    最近发现angular在使用input输入框的ng-model绑定scope变量的时候,发现,输入长串的数字将会出错.代码如下: <html> <head> <meta ...

  9. NAT ALG原理与应用

    1  NAT ALG简介 普通NAT实现了对UDP或TCP报文头中的的IP地址及端口转换功能,但对应用层数据载荷中的字段无能为力,在许多应用层协议中,比如多媒体协议(H.323.SIP等).FTP.S ...

  10. linux shell let, expr 命令详解

    linux命令之let.exprshell程序中的操作默认都是字符串操作,在运行数学运算符的时候可能得到意想不到的答案: var=1var=$var+1echo $var 将输出 1+1从这个例子中可 ...