MVVM. Is it a code smell when view model has properties with names show/hide/display that semantically belong to view?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/366053

  •  29-01-2021
  •  | 
  •  

Pergunta

I've lately been involved with WPF and looked into MVVM. I understand that view model shouldn't be aware of view.

However, sometimes I come across situation where my initial instinct is to write property in view model something like public bool ShowDialog { get; private set; } or public bool ShowPopUp { get; private set; }

Does it suggest that view's responsibility is creeping in view model and I should approach differently?

Foi útil?

Solução

Sometimes this can just be a naming issue.

For example, calling something ShowDialog in the ViewModel when what you mean is AskTheUserForAFilePath, which is independent of how the View handles that request. Similarly, ShowPopup when you mean InformTheUserOfThisEvent.

The end result of the communication will be the same but it allows multiple Views to handle the same interaction with the ViewModel in their own ways.

Outras dicas

Maybe.

If you were doing MVC I would say no. the purpose of the view model is to provide a model of the view which you can manipulate, query and test in code. It doesn't contain any business logic. But can contain view logic. ie when this is hidden show that.

You may well have a one to one mapping of View to ViewModel

In MVVM the view model tends to contain more businessy logic. You are expected to be able to apply multiple views to a single view model and have them all work. A ShowDetail property might make no sense for some Views

We then also have the practical aspect of WPF. Where Razor copes well with complex bindings,

visiblity=@{..complex expression with multiple conditionals and function calls}

Wpf doesnt,

Visiblity="{Binding PropertyWhichIsTheCorrectType Converter={Static/Relative namespace:thingIDeclaredinXAMLEarlierMaybe}}"

It makes you life far easier if you can just add a property to your VM and put the logic there.

You also have controls which are not fully supportive of the MVVM pattern, Behaviours, Converters and code behind etc. All of which can make your code messy if you don't have a common approach which you reuse across your codebase.

In conclusion I think that ShowDialogue properties are not the worst way to code. You are better off edging towards a more MVC+VM-C approach than trying to force WPF into a purist MVVM pattern

Licenciado em: CC-BY-SA com atribuição
scroll top