WPF关闭窗口,其中包含来自ViewModel类的MVVM

mik*_*_pl 0 c# wpf mvvm

在我看来,我有:

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

然后,在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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何管理这个问题,我想关闭ViewModel的当前窗口,因为我正在打开一个新窗口.

gre*_*k40 6

您可以设计窗口以获取用于发出关闭请求信号的上下文对象

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();
    }
}
Run Code Online (Sandbox Code Playgroud)