Should your ViewModel expose XAML elements as properties or not?

不羁岁月 提交于 2019-12-06 07:31:54

Because then that limits the ViewModel to be used only with a specific visual representation. Once you have the ViewModel emitting XAML, it puts design content into a developer's domain. This means that the designer using Expression Blend cannot edit design assets - and the designer/developer workflow is broken. Keeping the XAML on the page and using Value converters with data templating keeps the design separated from the code.

When your ViewModel exposes specific XAML it also limits that ViewModel to be used only in that specific instance and makes it less reusable.

Don't forget that you can use DataTemplates too. I can see some sense in keeping ValueConverters out of MVVM, but DataTemplates are all about transforming objects into GUI.

Your ViewModel can expose other objects (e.g. nested ViewModels) to the GUI, and the GUI can use <DataTemplate DataType="{x:Type SubViewModel}">... to map those objects to GUI.

Kent Boogaart

Does anyone see any reason why a ViewModel should not expose these rich XAML objects as Value Converters do?

Absolutely, because it undermines all the goals of MVVM:

  1. You're no longer unit testable, at least not easily.
  2. You no longer have separation between logic (view model) and presentation (view). Thus, designers and developers cannot easily collaborate.
  3. Code maintenance is more difficult because you've mixed the concerns together.

If I saw a view model returning a view, I wouldn't even classify it as MVVM.

I think one idea of mvvm/mvc/mvp etc. is to isolate the GUI code to one file/class. If you do this can you change to some other UI without rewriting the other objects? I think if you're passing around WPF specific objects the answer is no. It's a value judgment you'll have to make for your self.

There is no absolute 100% rule that works for this or many other concepts when you discuss them without the perspective of why the community's mind has shifted as it has in this direction. There is no 'assumed' truth or science in 'conventional wisdom' regardless of how new or compelling it is at the time.

In other words - just do the best with your team as if your good, your already getting pulled down far more in human concerns than anything as real as this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!