c# - Is right to have a XAML button send one message for the View and one for the VM (MVVM)? -


i'm developing simple contact manager wp 8.1. mv list of added contacts , has button create new contact (new contact view - ncv). nvc view has save button, , use button 2 proposes:

  1. add new contact list of contacts, happen vm
  2. send event code-behind file off view goback main view.

it works! , this, avoid vm have send event message view.

but wrong?

if wrong, there simple way avoid this?

there magic line:

<button content="save" command="{binding addnewcontactcommand}" click="button_click" /> 

your question opinion based , may wildly varying answers. comments "no, don't because you'll break mvvm pattern", depends on size , longevity , professionalism of project , programming style in general. in fact, using code behind view related logic fine in mvvm, although i'm sure die hard mvvm developers disagree statement.

however, if you'd prefer not use code behind, there other ways load views view model , can find common 1 explained in wpf mvvm navigate views question. there's there show here, general idea this:

all of view models should extend abstract base class, let's call baseviewmodel:

public baseviewmodel viewmodel { get; set; } 

in app.xaml, declare simple datatemplates connect views view models:

<datatemplate datatype="{x:type viewmodels:mainviewmodel}">     <views:mainview /> </datatemplate> <datatemplate datatype="{x:type viewmodels:personviewmodel}">     <views:personview /> </datatemplate> <datatemplate datatype="{x:type viewmodels:companyviewmodel}">     <views:companyview /> </datatemplate> 

now, wherever use 1 of baseviewmodel instances in application, these datatemplates tell framework display related view instead. can display them this:

<contentcontrol content="{binding viewmodel}" /> 

to switch new view, need set viewmodel property mainviewmodel class:

viewmodel = new personviewmodel(); 

please refer linked question further information on method.

of course, once have implemented system, you'll thinking 'how can change view model in main view model child view model?' answer can found in how call functions in main view model other view models? question.


Popular posts from this blog