Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I haveViewModel1 and View1 associated with it. I start dialog window from ViewModel2 (some another viewmodel) using IWindowManager object. The code from ViewModel2 class:

windowManager.ShowDialog(new ViewModel());

So, I have Dialog Window with View1 user control.

My answer is next - I can close that dialog window using red close button, but how to close it using my specific button (contained in View1 user control), something like "Cancel" button with close command (Command={Binding CancelCommand}), CancelCommand of course is contained in ViewModel1 class.

like image 824
Witcher Avatar asked Apr 10 '12 14:04

Witcher


People also ask

How do I close a ViewModel window?

<local:ViewModel/> </Window. DataContext> <StackPanel>

What is Caliburn Micro in WPF?

Caliburn. Micro is a small, yet powerful framework, designed for building applications across all XAML platforms. With strong support for MVVM and other proven UI patterns, Caliburn. Micro will enable you to build your solution quickly, without the need to sacrifice code quality or testability.


2 Answers

It's even easier if your view model extends Caliburn.Micro.Screen:

TryClose();
like image 116
Michal T Avatar answered Oct 10 '22 23:10

Michal T


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<ViewAttachedEventArgs> ViewAttached;
}

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

like image 42
nemesv Avatar answered Oct 11 '22 00:10

nemesv