WPF MVVM dialog example

后端 未结 6 1770
梦毁少年i
梦毁少年i 2020-12-04 07:48

Does anyone have any examples of showing a window dialog using MVVM (Prism)? - for example a configuration settings window when a command is executed.

All of the exa

6条回答
  •  有刺的猬
    2020-12-04 08:28

    The way I do this is using the mediator pattern also. When the ViewModel wants to show a dialog, it sends a message which is picked up by the application's main window. The message contains an instance of the ViewModel used by the dialog.

    The main window then constructs an instance of the dialog window, passes the view model to it and shows the dialog. The result of the dialog is passed back to the caller in the original message.

    It looks something like this:

    In your view model:

    DialogViewModel viewModel = new DialogViewModel(...);
    ShowDialogMessage message = new ShowDialogMessage(viewModel);
    
    _messenger.Broadcast(message);
    
    if (message.Result == true)
    {
        ...
    }
    

    In the main window codebehind:

    void RecieveShowDialogMessage(ShowDialogMessage message)
    {
        DialogWindow w = new DialogWindow();
        w.DataContext = message.ViewModel;
        message.Result = w.ShowDialog();
    }
    

    I hope this is enough to give you the idea...

提交回复
热议问题