Give some command to View in MVVM

前端 未结 5 1846
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 23:07

Let\'s imagine I have some user control. The user control has some child windows. And user control user wants to close child windows of some type. There is a method in user

5条回答
  •  無奈伤痛
    2020-11-28 23:30

    One way to achieve this would be for the view-model to request that the child windows should be closed:

    public class ExampleUserControl_ViewModel
    {
        public Action ChildWindowsCloseRequested;
    
        ...
    }
    

    The view would then subscribe to its view-model's event, and take care of closing the windows when it's fired.

    public class ExampleUserControl : UserControl
    {
        public ExampleUserControl()
        {
            var viewModel = new ExampleUserControl_ViewModel();
            viewModel.ChildWindowsCloseRequested += OnChildWindowsCloseRequested;
    
            DataContext = viewModel;
        }
    
        private void OnChildWindowsCloseRequested()
        {
            // ... close child windows
        }
    
        ...
    }
    

    So here the view-model can ensure the child windows are closed without having any knowledge of the view.

提交回复
热议问题