MVVM: when using code behind and when ViewModels

revyrevy ITMember

Hi, i am trying to understand how to correctly use the MVVM pattern inside Xamarin Forms. I am not sure when i should use code behind and when ViewModels. For example in case an event must be propagated to the UI (e.g. display an alert) this should be handled in code behind or in the view model?

Posts

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭
    edited November 2016

    @revy

    ViewModels should never know anything about the UI.

    A ViewModel might for example be the backing for a dozen different views, and as such can't be assured of anything specific to a given view.

    For example in case an event must be propagated to the UI (e.g. display an alert)

    Probably the wrong plan. Instead of an event you can raise a COMMAND.
    If the UI is meant to display something... Maybe the alert in this case is a label on the UI... Then you would bind the label to a VM property. When the property changes the UI updates automatically.

  • revyrevy ITMember

    In this case i want to show a toast message, thus not something that i have to embed in the UI, but i got your point.

    If i understand correctly, also in case of a login form it makes no sense to use the ViewModel if i need to extract typed username and password from the Entry fields. Also in this case it is better to use code behind instead of the ViewModel because i doesn't have to know the ui elements of the page. Let me know if this is incorrect.

    Thank you!

Sign In or Register to comment.