WPF (MVVM): Closing a view from Viewmodel?

后端 未结 11 1526
小鲜肉
小鲜肉 2020-12-12 16:23

Anybody come across a clever way of closing a view in a viewmodel using MVVM?

Maybe there is a way of using binding to signal the view (window) to close?

I w

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 16:56

    Not sure what MVVM framework you are using, but most contain some sort of messaging / notification solution that is easy have things register for messages which are sent. There is no reason that I can imagine that your view could not register for a message such as "CloseWindowsBoundTo" and the viewModel as the sender. Then in your view, you can just register for that message, and compare your current datacontext to the sender. If they match, close the window.

    Simple, and keeps your view abstracted from your viewmodel.

    Here would be my approach using MVVM-light toolkit:

    In the ViewModel:

    public void notifyWindowToClose()
    {
        Messenger.Default.Send(
            new NotificationMessage(this, "CloseWindowsBoundToMe")
        );
    }
    

    And in the View:

    Messenger.Default.Register(this, (nm) =>
    {
        if (nm.Notification == "CloseWindowsBoundToMe")
        {
            if (nm.Sender == this.DataContext)
                this.Close();
        }
    });
    

提交回复
热议问题