数据注释和WPF验证 [英] Data annotation and wpf validation
问题描述
有什么方法可以将数据注释用作WPF中的验证来源?我希望能够定义一个类,例如:
Is there any way that I use data annotation as the source of validation in WPF? I want to be able to define a class such as:
class myData
{
[Required]
[MaxLength(50)]
public string Name{get;set;}
}
然后将其绑定到视图中的字段,并且wpf验证用户为此字段输入了一些值,并确保其长度不大于50。我知道我可以编写一个验证器为此,但是如果我将maxLength更改为60,则需要在验证器中进行更改,并且我不想在其他位置进行更改。
And then bind it to a field in a view and the wpf validate that user enter some value for this field and also make sure that its length is not greater than 50. I know that I can write a validator for this, but then if I change the maxLength to say 60, then I need to change it in validator and I don't want to have changes in different places.
推荐答案
您需要创建该类的元数据定义。您将需要以下内容:
You need to create a "metadata" definition of the class. You'll need something like this:
[MetadataTypeAttribute(typeof(MyClass.MyClassMetadata))]
public partial class MyClass
{
internal sealed class MyClassMetadata
{
// Metadata classes are not meant to be instantiated.
private MyClassMetadata()
{
}
[Required]
[MaxLength(50)]
public string Name{ get; set; }
}
}
此类将必要的元数据扩展为支持验证。
This extends the class with the necessary meta data to support the validation.
这篇关于数据注释和WPF验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!