mike_pl
mike_pl

Reputation: 121

WPF Close window with MVVM from ViewModel class

In my view I have:

<Button Grid.Column="2" x:Name="BackBtn" Content="Powrót" Command="{Binding ClickCommand}" Width="100" Margin="10" HorizontalAlignment="Right"/>

Then, in ViewModel :

public ICommand ClickCommand
{
    get
    {

        return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), _canExecute));
    }
}

private void MyAction()
{
    MainWindow mainWindow = new MainWindow(); // I want to open new window but how to close current?
    mainWindow.Show();
    // how to close old window ?
}

namespace FirstWPF
{
    public class CommandHandler : ICommand
    {
        private Action _action;
        private bool _canExecute;
        public CommandHandler(Action action, bool canExecute)
        {
            _action = action;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            _action();
        }
    }
}

I have no idea how to manage that problem, I want to close current window form ViewModel, because I am opening a new one.

Upvotes: 0

Views: 9082

Answers (1)

grek40
grek40

Reputation: 13458

You can design your window to take in context object that is used to signal a close request

public interface ICloseable
{
    event EventHandler CloseRequest;
}

public class WindowViewModel : BaseViewModel, ICloseable
{
    public event EventHandler CloseRequest;
    protected void RaiseCloseRequest()
    {
        var handler = CloseRequest;
        if (handler != null) handler(this, EventArgs.Empty);
    }
}


public partial class MainWindow : Window
{
    public MainWindow(ICloseable context)
    {
        InitializeComponent();
        context.CloseRequest += (s, e) => this.Close();
    }
}

Upvotes: 9

Related Questions