Should the MVVM ViewModel perform type conversion/validation?

后端 未结 5 1005
闹比i
闹比i 2021-01-31 08:19

We\'re just getting into MVVM in WPF.

We have implemented our ViewModels with \'strongly typed\' properties (int, double? etc.) that we bind to in the view.

Type

5条回答
  •  借酒劲吻你
    2021-01-31 08:56

    This is a good question, and I can certainly see both sides of the discussion.

    My thought is that what you're really looking for is a proper NumericInputControl that you can use in your xaml. This will provide a better user experience because your users won't be able to accidentally enter text in a number field and, because the control constrains input without validating it, you can maintain the more strongly-typed ViewModel.

    I'm not sure how you'd want to go about implementing one, I know that the classic spinner/NumericUpDown controls are falling out of favor because they aren't touch-friendly, but I don't believe that the introduction of such a control will violate the purity of the design approach or your ViewModels. You'll receive a number that you can then range-validate in the appropriate place, supply feedback via IDataErrorInfo as usual, and so forth. :) This technique lets you get the best of both worlds without any real drawbacks (except the creation of a numeric control).

提交回复
热议问题