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

时间:2017-03-03 17:20:29

标签: c# wpf mvvm

在我看来,我有:

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

然后,在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();
        }
    }
}

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

2 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:0)

之前在这些论坛上已经多次回答过。

在我看来,最清晰的解决方案是附加财产,如this question的最高评级回答所述。