简体   繁体   中英

How to handle CloseDocument command in MVVM

So I have a main window that shows MDI type interface with multiple document tabs open inside it (just like VS). Both the main window and the document windows have their respective VMs. The CloseDocument command is handled in the document, but needs to tell main window VM about it, so that main window VM could update its Documents collection. What is the proper way of managing this in MVVM? A few ideas that I have:

  1. I could add an event to document VM that is raised just before closing. I could then add its event listener to main window VM for each new document that I add.
  2. I could move the CloseDocument command to main window VM, but ideally the event doesn't belong there.
  3. I could pass reference of the Documents collection to my document VM, so that it updates the collection before closing itself.

Which among these (or if someone has a better one) should be used while following MVVM practices?

I think I would pick solution 1. If you use MVVM Light then you can apply Messenger type to pass the information between Documents.

Each document would have a Command with reference to this method:

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

And in the VM of main Window you would have something like this: (in constructor)

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

... but this could works only if you have Messenger, otherwise you could use events, but then I am afraid you need to use strong references between VMs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM