IDataErrorInfo vs ValidationRule vs Exception

后端 未结 3 1784
故里飘歌
故里飘歌 2020-12-09 16:31

Can anyone tell me which is a better approach for Validation in WPF.

  1. Implementing IDataErrorInfo
  2. Creating ValidationRule
  3. Throwing Exceptions
3条回答
  •  鱼传尺愫
    2020-12-09 17:08

    I have a slightly different take on the topic, than the views presented in the other two answers:

    ValidationRule

    • This is appropriate for validation that needs to be done before the source of a binding is updated. Reasons you might like to do this include being able to present a specific error message to the user, especially messages that relate to values before data conversion, or validating data that has to be converted.

    • As noted in other answers, it's also somewhat easier to share validation among multiple controls, as you can do things like create a single ValidationRule which is used in multiple bindings, or use a BindingGroup to provide a single ValidationRule that checks multiple bindings at once.

    IDataErrorInfo or INotifyDataErrorInfo

    • This puts validation into the view model, and is appropriate for scenarios where it is allowable for an illegal value to be stored in the view model. Specific error messages can be provided to the user via this interface.

    • Validation is available for any client of the view model implementation, providing better reuse for such validation.

    • Reuse of validation rules is somewhat less convenient, but not impossible by any means. You just need to implement your own helper methods or objects to perform the validation as you like.

    Exceptions

    • The other answers eschew exceptions for validation, based on performance concerns. However, it's been my experience that exception handling in UI scenarios is generally just fine. In spite of the extra overhead of exception handling, it still happens way faster than the user is capable of noticing (unverified "anecdotes" notwithstanding).

    • One important aspect of exceptions is that it gives you much of the benefit of implementing an error-notification interface on your view model, while still preventing invalid values from being set on the view model properties. In other words, you may have validation scenarios where ValidationRule happens too early and IDataErrorInfo happens too late. Throwing exceptions from property setters would address those scenarios.

    Bottom line: each validation technique has its own pros and cons, and is appropriate for specific scenarios. None are uniformly superior to any of the others. It depends a lot on what kind of validation you are trying to do, and where you want to see that logic executed.

提交回复
热议问题