Binding DataContext to ValidationRule

前端 未结 7 1879
粉色の甜心
粉色の甜心 2021-02-04 11:33

I have a custom ValidationRule that requires access to the ViewModel in order to validate a supplied value in conjunction with other properties of the ViewModel. I previously tr

相关标签:
7条回答
  • 2021-02-04 12:16

    I would avoid using validation rules. If you need access to the information in the viewmodel to perform validation, then it's better to put the validation logic in the viewmodel itself.

    You can make your viewmodel implement IDataErrorInfo, and simply turn on data error info-based validation on the binding.

    Even if you don't run into this (very common) problem of needing contextual information, validation rules aren't really a great way to express validation: validation rules are usually related to business logic, or at least to semantic aspects of your information. Xaml seems like the wrong place to put such things - why would I put a business rule in the source file whose main job is to determine the layout and visual design of my application?

    Validation logic belongs further down in your app. Even the viewmodel might be the wrong layer, but in that case, you can simply make it the viewmodel's responsibility to work out where to find the validation logic.

    0 讨论(0)
提交回复
热议问题