How to close dialog window from viewmodel (Caliburn+WPF)?

前端 未结 3 429
醉话见心
醉话见心 2020-12-05 14:32

I haveViewModel1 and View1 associated with it. I start dialog window from ViewModel2 (some another viewmodel) using IWindowManager obj

3条回答
  •  时光取名叫无心
    2020-12-05 15:04

    You can get the current view (in your case the dialog window) with implementing the IViewAware interface on your ViewModel. Then you can call Close on the the view (the Window created as the dialog) when your command is executed.

    The easiest why is to derive from ViewAware:

    public class DialogViewModel : ViewAware
    {
        public void ExecuteCancelCommand()
        {
            (GetView() as Window).Close();
        }
    }
    

    If you are not allowed to derive you can implement it yourself:

    public class DialogViewModel : IViewAware
    {
        public void ExecuteCancelCommand()
        {
            dialogWindow.Close();
        }
    
        private Window dialogWindow;
        public void AttachView(object view, object context = null)
        {
            dialogWindow = view as Window;
            if (ViewAttached != null)
                ViewAttached(this, 
                   new ViewAttachedEventArgs(){Context = context, View = view});
        }
    
        public object GetView(object context = null)
        {
            return dialogWindow;
        }
    
        public event EventHandler ViewAttached;
    }
    

    Note: I've used Caliburn.Micro 1.3.1 for my sample.

提交回复
热议问题