Should the MVVM ViewModel perform type conversion/validation?

后端 未结 5 1007
闹比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 09:09

    Should the MVVM ViewModel perform type conversion/validation?

    Yes.

    The view model is an abstraction layer between the view and the model - the perfect spot to perform any type conversions (instead of cumbersome value converters). Validation should absolutely occur as part of the view model.

    We use our View Model to handle the conversions as much as possible for data types. This reduces the need for a value converter to some very specific circumstances. You want to expose whatever type is easiest for the view to consume. This has been working well.

    The one specific question you raised:

    If, say, a non-numeric value is entered in a text box bound to a numeric property, the conversion fails, the property is never set, and we never get a chance to provide proper feedback to the user. Worse, the property retains its current value, leading to a mismatch between what's displayed in the view and what's actually in the ViewModel.

    might be handled by exposing your view model type as a nullable type. This should still allow the underlying source to be updated, even if invalid data is entered, and trigger validation. This worked in a similar situation we had with DateTime and a date time picker.

    Keep the view as dumb. We don't have official designers, our developers are our designers, so keeping the view dumb has some benefits:

    • We (developers) get to keep our sanity (XAML is somewhat less verbose)
    • Business logic (including validation) stays in the view model and can enable testing

    Good Luck!

    -Z

提交回复
热议问题