WPF (MVVM): Closing a view from Viewmodel?

后端 未结 11 1550
小鲜肉
小鲜肉 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:49

    You can also do this using event. Though you need like 3 lines of codes in your view code behind (some MVVM purist don't like this);

    In your viewmodel, you create an event that the view can subscribe to:

        public event CloseEventHandler Closing;
        public delegate void CloseEventHandler();
        private void RaiseClose()
        {
            if (Closing != null)
                Closing();
        }
    

    In your, view you subscribe to the event after your initializecomponent method as below:

            public View
            {
               *//The event can be put in an interface to avoid direct dependence of the view on the viewmodel. So below becomes
                //ICloseView model = (ICloseView)this.DataContext;*
                ProgressWindowViewModel model = (ProgressWindowViewModel)this.DataContext;
                model.Closing += Model_Closing;
            }
            private void Model_Closing()
            {
                 this.Close();
            }
    

    You just simply call RaiseClose() when you are ready to close the View from the ViewModel.

    You can even use this method to send message to the view from the viewmodel.

    The event can be put in an interface to avoid direct dependence of the view on the viewmodel.

提交回复
热议问题