How to handle CloseDocument command in MVVM

So I have a main window that has an MDI type interface with multiple document tabs open inside it (just like VS). The main window and document window have corresponding virtual machines. The CloseDocument command is processed in the document, but needs to be told to the main window VM so that the main window virtual machine can update the document collection. What is the correct way to manage this in MVVM? Several ideas I have:

  • I could add an event to document the virtual machine that was created before the shutdown. Then I could add my event listener to the main VM window for each new document added.
  • I can bring the CloseDocument command to the main VM window, but ideally this event does not belong.
  • I can pass a document collection reference to my VM document so that it updates the collection before it is closed.

Which one (or if anyone has a better one) should I use with the following MVVM techniques?

+3


source to share


1 answer


I think I would go for solution 1. If you are using MVVM Light, you can use the Messenger type to transfer information between documents.

Each document will have a command with a link to this method:

private void CloseDocumentExecuteCommand()
{
    var message = new DocumentCloseMessage() { Document = this};
    Messenger.Default.Send<DocumentCloseMessage>(message);
}

      



And in the VM of the main window, you will have something like this: (in the constructor)

Messenger.Default.Register<CloseMessage>(this, (msgData) => this.CloseMessageReceived(msgData));

      

... but this can only work if you have Messenger, otherwise you can use events, but then I'm afraid you need to use strong links between VMs.

+1


source







All Articles