【发布时间】:2020-08-25 02:45:54
【问题描述】:
您好,我是 C# 新手,我创建了一个 WPF 表单,它接收 csv 并将其保存在数据库中。现在我想知道是否有一个Validation Library 可以用来使这些字段检查更容易?就像我想实现一个必需的字段或其他东西,如果不需要该字段,它将引发错误。我怎样才能做到这一点?我读过一些类似这样的代码
[Required] // Not sure if this is the correct format
public string Name()
{
get;set;
}
所以基本上我在考虑一种中间件类型的验证,我只需将[Required] 属性放在模型类中,它就会为我进行验证。有这种事吗?
更新:我所说的验证的意思是,当我选择一个 csv 文件后,它将读取每行/列,现在每一列都将像 ex.对于column[0](假设这是名称字段),当读取此字段并将其分配给变量时,应在继续分配给变量之前对其进行验证。不知道这是否可能更多是这样的
string[] content = row.Split('|');
Customer customer = new Customer(content);
Lis<KeyValuePair<string, string>> rowList = Converter.ToKeyValuePair(customer);
这是Customer 类的代码
class Converter
{
public static List<KeyValuePair<string,string>> ToKeyValuePair(Customer customer)
{
List<KeyValuePair<string, string>> rowList = new List<keyValuePari<string, string>>();
rowList.Add(new KeyValuePair<string, string>('name', customer.Name));
}
return rowList;
}
// 类客户
class Customer
{
private string _name;
public Customer(string[] content)
{
this.Name = content[0];
}
[Required] // Maybe some auto validation here where when the property is accessed it should be validated immediately
public string Name
{
get { return _name; }
set {
// I'm thinking of some validation here?
_name = value;
}
}
}
正如您在我的示例中看到的,我希望每当访问像 this.Name = content[0] 这样的属性时,它会自动验证内容是否有价值
【问题讨论】:
-
您的意思是在 WPF 表单中验证模型吗?就像在输入有效之前禁用“保存”或“提交”按钮?
-
@IvanVargas 会更新我的问题
-
This 可能会帮助你
-
@IvanVargas,这是针对 web(asp.net) 的。 WPF 是桌面平台。
-
@MadzQuestioning,在 wpf 中,您应该在模型/视图模型上使用 IDataErrorInfo 接口而不是属性。