可能重复:
The best approach to create new window in WPF using MVVM
Hello Friends,
我有两个视图 MainWindowView 和 AddCustomerView 。我在MainwindowView.xmal中有包含按钮的菜单。
如何通过点击按钮从MainWindowViewModel弹出 AddCustomerView。
我的App.xmal.cs for Startup code是..
base.OnStartup(e);
MainWindow window = new MainWindow();
var viewModel = new MainWindowViewModel();
window.DataContext = viewModel;
window.Show();
在buttonexecute代码中显示AddCustomerView的代码是什么。
public void AddNewCustomerWindowExecute() //This is button handler
{
// How to show AddCustomerView from MainWindowViewModel
}
答案 0 :(得分:22)
可能是最简单的方法。
private void AddCustomerView_Click(object sender, RoutedEventArgs e)
{
AddCustomerView view = new AddCustomerView(data);
view.Show();
}
这有一个缺点:它需要大量手动编码。
public class MainWindowViewModel
{
public event EventHandler AddCustomerViewShowed;
public void AddNewCustomerWindowExecute()
{
if (AddCustomerViewShowed != null)
AddCustomerViewShowed(this, EventArgs.Empty);
}
}
在视图中处理它
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();
}
}
某些MVVM框架(例如MVVM Light)使用此模式。
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(...));
}
}
答案 1 :(得分:3)
查看这个“深潜MVVM视频”。 Laurent Bugnion展示了IDialogService的概念并很好地解释了这些概念......加上源代码也应该可用...... 这些概念也适用于wpf
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
HTH