前言
在使用mvvm模式时,属性跟页面空值值绑定,我们在做一些配置页面时常常需要对用户输入的值进行校验。如果一个个控件的值去校验,非常不友好。因此本文针对这种情况采用自定义特性解决,如果有别方便的方法,欢迎留言。
代码
定义
这里继承Attribute类型,使用enum限制用户输入类型
public class CheckAttribute : Attribute
{
public CheckAttribute(string name, TypesEnum types)
{
this.Name = name;
this.types = types;
}
public TypesEnum types { get; set; }
public string Name { get; set; }
}
public enum TypesEnum
{
Nonull = 1,
Floating = 2,
nullorInterge = 3,
}
定义
这里对名称进行省略了Attribute
[Check("参数编码", TypesEnum.Nonull)]
public string ParamCode
{
get { return _paramCode; }
set
{
if (_paramCode == value) return;
if (_paramCode != null && IsColour)
{
ParamCodeColour = "#ff1047";
}
_paramCode = value;
OnPropertyChanged();
}
}
private string _paramName;
[Description("参数名称")]
[Check("参数名称", TypesEnum.Nonull)]
public string ParamName
{
get { return _paramName; }
set
{
if (_paramName == value) return;
if (_paramName != null && IsColour)
{
ParamNameColour = "#ff1047";
}
_paramName = value;
OnPropertyChanged();
}
}
方法
检验属性值
private string Checked<T>(T model)
{
string msg=null;
var properties = model.GetType().GetProperties();
foreach (var item in properties)
{
if (item.IsDefined(typeof(CheckAttribute), true))
{
var attribute = item.GetCustomAttribute<CheckAttribute>();
switch (attribute.types)
{
case TypesEnum.Nonull:
if (string.IsNullOrEmpty(item.GetValue(model).ToString()))
{
msg = attribute.Name + "不能为空!";
return msg;
}
break;
case TypesEnum.nullorInterge:
if (!Integer(item.GetValue(model).ToString()))
{
msg = attribute.Name + "请填写空或正整数!";
return msg;
}
break;
case TypesEnum.Floating:
if (!NfloatInteger(item.GetValue(model).ToString()))
{
msg = attribute.Name + "请填写空或数值!";
return msg;
}
break;
}
;
}
}
return "";
}
public static bool NfloatInteger(string strPrice)
{
string strRegex = @"^(-?\d+)(\.\d+)?$";//浮点数
Regex re = new Regex(strRegex);
if (string.IsNullOrEmpty(strPrice))
{
return true;
}
if (re.IsMatch(strPrice))
{ return (true); }
else
{ return (false); }
}
public static bool Integer(string strPrice)
{
string strRegex = @"^[0-9]\d*$";//正整数
Regex re = new Regex(strRegex);
if (string.IsNullOrEmpty(strPrice))
{
return true;
}
if (re.IsMatch(strPrice))
{ return (true); }
else
{ return (false); }
}
使用
校验的类传入方法
var reult = Checked(DataResource);
if (!string.IsNullOrEmpty(reult))
{
tb_Tips.Text = "提示:"+reult;
return true;
}
结论
个人学习使用,有不当之处请多多指教