Where "should" view logic resides normally? In the view (including code behind) or in the viewmodel?
By logic I understand anything what is used to modify view (makes it dynamic), changing its elements properties: Visibility
, IsEnabled
, Content
, etc. based on some conditions.
I am struggling between choosing correct statement:
ViewModel is responsible for all view "properties", if view needs some logic - this should be a job of viewmodel.
View is a viewmodel presentation, viewmodel only needs bare minimum to expose model, the logic thus should be a part of the view.
Logic in the view.
An example, to display some text:
<Grid Visibility="{Binding TextAvailable, Converter=...}">
<TextBlock Text="{Binding Text}" Visibility="{Binding TextOk, Converter=...}" />
</Grid>
By looking at this xaml you know there are 2 properties in viewmodel: TextAvailable
and TextOk
, used to conditionally display Text
.
Same can be achieved using data triggers. The way is irrelevant, the main point is: logic is in the view. One have to go through view thoroughly to understand both: the logic and implementation.
Logic in the viewmodel.
Xaml is easier:
<TextBlock Text="{Binding Text}" Visibility="{Binding ShowText, Converter=...}" />
and the logic is in the viewmodel:
public bool ShowText => TextAvailable && TextOk;
but this will require notification support, often subscribing/unsubscribing to events (using weak events if deterministic unsubscribing is complicated), to be able to tell the view OnPropertyChanged(nameof(ShowText))
if any relevant property is changed. Thus implementation is well spread among many methods/properties.
I personally prefer to have simple viewmodel and rather complicated view (xaml), full of logic. Recently I found a way to make logic looking really cool (no additional elements and easier to see).
I understand what both approaches can be used and question thus is rather opinion based, but I don't want to mix both approaches in crazy proportions in my software. Which way is more clean and would be better accepted by another MVVM programmer? What should I prefer and why?