0
votes

I am trying to close a usercontrol from a viewmodel that was opened as a window/dialog in a viewmodel button command.

Open a usercontrol as window/dialog: MainWindow >> Button >> Command via MainWindowViewModel >> Show usercontrol as window/dialog

Close the usercontrol that was opened in the above step: ????

Also I am wondering if I am violating the mvvm pattern, so if someone can please provide me with some proper examples as I am fairly new to the wpf MVVM pattern.

mainwindow button command in viewmodel:

private void ExecuteOtherMethod(object parameter)
    {


        registerWindow win = (registerWindow)Application.Current.MainWindow;
        //win.pp.IsOpen = true;
        win.bankRectangle.Visibility = Visibility.Visible;
        Window window = new Window

        {

            WindowStyle = WindowStyle.None,
            SizeToContent = SizeToContent.WidthAndHeight,
            ResizeMode = ResizeMode.NoResize,
            Content = new otherOptionsView()
        };
        window.Owner = win;
        window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
        window.ShowDialog();


    }

usercontrol viewmodel to close the usercontrol:

 private void ExecuteMethod(object parameter)
    {

        //otherOptionsView newview = new otherOptionsView();
        //Window parentWindow = (Window)newview.Parent;
        //parentWindow.Close();
        var displayViews = App.Current.Windows.OfType<otherOptionsView>();
        if (displayViews.Any())
            displayViews.First().Close();
        registerWindow win = (registerWindow)Application.Current.MainWindow;
        win.bankRectangle.Visibility = Visibility.Collapsed;


    }
2

2 Answers

0
votes

One way is to not have a window at all (if it is not the main window) as in the accepted answer here Handling Dialogs in WPF with MVVM. Have a free floating user control in your window and bind its visibility to a boolean in the view model.

You can also raise an event and handle it in the view as in WPF (MVVM): Closing a view from Viewmodel? .

Another way is to use a ViewModel messenger or a Mediator. This requires code-behind in the view, and is not normally meant for communication between the view model and the view. You register the view to the mediator class and listens for that specific "close" request sent by the view model through the mediator. As in Use MVVM Light's Messenger to Pass Values Between View Model

Also if you are actually trying to close your main window why not use Application.Current.Shutdown() ?

0
votes

For window management you can always use the nuget package 'MvvmDialogs', it is specially designed towards helping you with window parent child relations, and has a fairly large collection of sample applications.