需要有关 MVVM 验证的建议
我正在将现有的一个应用程序转换为 MVVM 模式以改进其结构,但我对于什么是进行数据验证的最佳方法感到有点困惑。
目前,该应用程序使用数据绑定来链接 UI 和代码,并使用一些验证规则和值转换器,这些规则和值转换器可以在类似的值上重用(每个值一个用于日期等)。
在阅读 MVVM 时,我遇到了 IDataErrorInfo,我发现它很有吸引力,因为它可以将验证保持在视图之外,从而在设置绑定等时稍微减少重复代码,并允许更具体的错误消息。
另一方面,如果验证失败,ValidationRules 会阻止绑定数据的传输,这是我需要的,因为我只希望模型值更改提供的新的有效值。
我主要担心的是,如果我在视图模型中限制太多,这将使视图中的事情变得困难 - 在一般情况下将事情限制到舒适的水平,然后在需要更多灵活性的特定情况下进行补救是个好主意吗?景色?
所以我的主要问题是,将验证和转换放在视图模型的属性中或坚持我的验证规则和值转换器(或两者之间的某种折衷)会更好吗?
I'm converting one of my existing applications to the MVVM pattern to improve its structure and I'm a bit torn on what would be the best way to do the data validation.
Currently the application uses data binding to link the UI and code and uses a few validation rules and value converters which can be reused on similar values (one of each for dates, etc.).
Whilst reading up on MVVM I've come across IDataErrorInfo, which I find attractive because it would keep validation out of the view, thus slightly reducing repetitive code when setting bindings, etc. and allow for more specific error messages.
ValidationRules on the other hand block the transfer of binding data if the validation fails, which I need because I only want the model values to change a new, valid value is supplied.
My major concern is that if I restrict things too much in the viewmodel that this will make things difficult in the view - is it a good idea to restrict things to a comfortable level in the general case and then remedy specific cases that need more flexibility in the view?
So my main question is, would it be better to put validation and conversion in the properties of the viewmodel or stick with my validationrules and valueconverters (or some compromise in between)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用
IDataErrorInfo
在视图模型中实现所有验证,并让视图模型根据属性是否有效来决定是否应将属性更改传递给模型。因此,典型的 setter 看起来像这样:我从来没有在视图中实现验证或值转换。这简直就是自找麻烦。
I implement all validation in the view model, using
IDataErrorInfo
, and let the view model decide whether or not it should pass property changes to the model based on whether the property is valid. So a typical setter looks something like:I never, ever implement validation or value conversion in the view. That just seems like begging for trouble.
我会使用组合。
我在实体中使用 Idataerrorinfo(验证不在视图模型中)作为核心可重用业务规则。我的实体也可以通过这种方式验证自己。
然后,我将视图 ValidationRules 用于绑定错误不会进入我的实体的位置,例如当字符串用作整数文本框中的输入时。
I would use a combination.
I use Idataerrorinfo in my entities (validation is not in the viewmodel) for core re-usable business rules. My entities can also validate themselves this way.
I then use view ValidationRules for places where a binding error will not make it to my entity such as when a string is used as input in a integer textbox.