WPF MVVM-如何在单击按钮时从MainWindowViewModel中显示视图 [英] WPF MVVM - How to Show a view from MainWindowViewModel upon Clicking on button
问题描述
可能重复:
使用WPF在WPF中创建新窗口的最佳方法MVVM
Possible Duplicate:
The best approach to create new window in WPF using MVVM
你好朋友,
我有两个视图 MainWindowView 和 AddCustomerView .我在MainwindowView.xmal中有包含按钮的菜单.
I have two view MainWindowView and AddCustomerView. I have menu containing buttons in MainwindowView.xmal.
如何通过单击按钮从MainWindowViewModel中弹出 AddCustomerView.
How could i popup AddCustomerView from MainWindowViewModel by clicking on button.
我的启动代码App.xmal.cs是..
My App.xmal.cs for Startup code is..
base.OnStartup(e);
MainWindow window = new MainWindow();
var viewModel = new MainWindowViewModel();
window.DataContext = viewModel;
window.Show();
在按钮执行代码中显示AddCustomerView的代码是什么.
What is the code for showing AddCustomerView in buttonexecute code.
public void AddNewCustomerWindowExecute() //This is button handler
{
// How to show AddCustomerView from MainWindowViewModel
}
推荐答案
在视图中处理
可能是最简单的方法.
Handle it in the view
Probably the most simple approach.
private void AddCustomerView_Click(object sender, RoutedEventArgs e)
{
AddCustomerView view = new AddCustomerView(data);
view.Show();
}
ViewModel公开一个事件
这有一个缺点:它需要大量的手动编码.
ViewModel exposes an event
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);
}
}
在视图中处理
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 )使用此模式.
Mediator pattern
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(...));
}
}
这篇关于WPF MVVM-如何在单击按钮时从MainWindowViewModel中显示视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!