WPF MVVM - How to Show a view from MainWindowViewM

2019-01-31 15:31发布

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
 }

标签: wpf mvvm
2条回答
狗以群分
2楼-- · 2019-01-31 16:11

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

查看更多
Explosion°爆炸
3楼-- · 2019-01-31 16:18

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 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);
    }
}

Handle it in the view

var viewModel = new MainWindowViewModel();
viewModel.AddCustomerViewShowed += (s, e) => new AddCustomerView(data).Show();

Controller that handles all your 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 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(...));
    }
}
查看更多
登录 后发表回答