0

I'm using a MVVM ViewModel first approach with Stylet and I'm struggling to close a window from it's ViewModel.

In the Stylet Wiki it states that I can use:

Screen.RequestClose

I have the following code:

public class MdExportViewModel : Screen
{
    public MdExportViewModel()
        {
            if(canExport == true)
            {
                this.RequestClose();
            }
        }
}

When I try to call the 'RequestClose' I get the following error:

System.InvalidOperationException: 'Unable to close ViewModel Drain.ViewModels.Windows.MdExportViewModel as it must have a conductor as a parent (note that windows and dialogs automatically have such a parent)'

I've tried adding the Conductor<T> as follows:

public class MdExportViewModel : Conductor<IScreen>

But I get the same error. I didn't really understand how a conductor should be used in this instance. I assumed my origional attempt would work since note that windows and dialogs automatically have such a parent.

What am I doing wrong here? Other answers to similar questions use complicated workarounds, but I'd like to use a Stylet method to keep things consistent and simple.

EDIT:

The window is opened in another viewmodel as follows:

    public void ExportMD()
    {

        MdExportViewModel MdExportViewModel = new(networkMain, DesignCriteriaViewModel)
        {
            Parent = this
        };
       
        this.windowManager.ShowWindow(MdExportViewModel);
    }
Richard
  • 439
  • 3
  • 25
  • How did you show that window? I'm guessing you didn't use `IWindowManager.ShowWindow(new MdExportViewModel())` or similar? – canton7 Feb 02 '22 at 09:15
  • I've added an edit to show how the window is opened – Richard Feb 02 '22 at 10:12
  • Why are you doing `Parent = this` there? That should be getting overwritten straight away by the `WindowManager` – canton7 Feb 02 '22 at 10:14
  • Aha, the problem is that you're trying to close the `MdExporyViewModel` from its constructor. The framework hasn't yet had a chance to set up its parent properly at that point. Override the `OnInitialActivate` and put your close logic in there -- that's called as soon as the window is shown. Or, you know, change your logic so that you're not showing a window then immediately closing it again. – canton7 Feb 02 '22 at 10:18
  • I see, I think I'm going about this the wrong way then. If I add a button to the window which triggers the 'this.RequestClose();' it works just fine. But if I call it in 'OnInitialActivate()' it seem to work, but then 'ShowWindow' fails as it's trying to open something that's already closed. I'm trying to open a window, that shows progress, then closes if no issue has been identified. – Richard Feb 02 '22 at 12:25
  • 1
    All sorted thanks. Placing the close command in 'OnViewLoaded()' does exactly what I need. – Richard Feb 02 '22 at 13:15

0 Answers0