Possible Duplicate:
The best approach to create new window in WPF using MVVM
Hello Friends,
I have two view MainWindowView and AddCustomerView. I have menu containing buttons in MainwindowView.xmal.
How could i popup AddCustomerView from MainWindowViewModel by clicking on button.
My App.xmal.cs for Startup code is..
base.OnStartup(e);
MainWindow window = new MainWindow();
var viewModel = new MainWindowViewModel();
window.DataContext = viewModel;
window.Show();
What is the code for showing AddCustomerView in buttonexecute code.
public void AddNewCustomerWindowExecute() //This is button handler
{
// How to show AddCustomerView from MainWindowViewModel
}
Probably the most simple approach.
private void AddCustomerView_Click(object sender, RoutedEventArgs e)
{
AddCustomerView view = new AddCustomerView(data);
view.Show();
}
This has one drawback: it requires lots of manual coding.
public class MainWindowViewModel
{
public event EventHandler AddCustomerViewShowed;
public void AddNewCustomerWindowExecute()
{
if (AddCustomerViewShowed != null)
AddCustomerViewShowed(this, EventArgs.Empty);
}
}
Handle it in the view
var viewModel = new MainWindowViewModel();
viewModel.AddCustomerViewShowed += (s, e) => new AddCustomerView(data).Show();
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();
}
}
Some MVVM frameworks (e.g. MVVM Light) use this pattern.
public class App // or in the 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(...));
}
}
Check out this "deep dive MVVM video". Laurent Bugnion shows the Concept of the IDialogService and explains the concepts very well... plus the source code should also be available... The concepts apply also to wpf
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With