WPF MVVM - How to Show a view from MainWindowViewModel upon Clicking on button -


possible duplicate:
the best approach create new window in wpf using mvvm

hello friends,

i have 2 view mainwindowview , addcustomerview. have menu containing buttons in mainwindowview.xmal.

how popup addcustomerview mainwindowviewmodel clicking on button.

my app.xmal.cs startup code is..

base.onstartup(e); mainwindow window = new mainwindow(); var viewmodel = new mainwindowviewmodel(); window.datacontext = viewmodel; window.show(); 

what code showing addcustomerview in buttonexecute code.

 public void addnewcustomerwindowexecute() //this button handler  {      // how show addcustomerview mainwindowviewmodel  } 

handle in view

probably simple approach.

private void addcustomerview_click(object sender, routedeventargs e) {     addcustomerview view = new addcustomerview(data);     view.show(); } 

viewmodel exposes event

this has 1 drawback: requires lots of manual coding.

public class mainwindowviewmodel  {     public event eventhandler addcustomerviewshowed;      public void addnewcustomerwindowexecute()     {         if (addcustomerviewshowed != null)             addcustomerviewshowed(this, eventargs.empty);     } } 

handle in view

var viewmodel = new mainwindowviewmodel(); viewmodel.addcustomerviewshowed += (s, e) => new addcustomerview(data).show(); 

controller handles views

public class controller : icontroller {     public void addcustomer()     {         addcustomerview view = new addcustomerview(data);         view.show();     } }  public class mainwindowviewmodel  {     icontroller controler;      public mainwindowviewmodel(icontroller controller)     {         this.controller = controller;     }      public void addnewcustomerwindowexecute()     {         controller.addcustomer();     } } 

mediator pattern

some mvvm frameworks (e.g. mvvm light) use pattern.

public class app // or in view or somewhere else {     public void registermessenger()     {         messenger.default.register<addcustomermessage>(this, processaddcustomermessage);                 }      private void processaddcustomermessage(addcustomermessage message)     {         addcustomerview view = new addcustomerview(data);         view.show();     } }  public class mainwindowviewmodel  {     public void addnewcustomerwindowexecute()     {         messenger.default.send(new addcustomermessage(...));     } } 

Comments