【问题标题】:WPF Close window with MVVM from ViewModel classWPF 使用 ViewModel 类中的 MVVM 关闭窗口
【发布时间】:2017-03-03 17:20:28
【问题描述】:

在我看来,我有:

<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,因为我正在打开一个新窗体。

【问题讨论】:

  • 您是说要在打开新窗口之前致电Application.Current.MainWindow.Close();
  • 只是一个旁注——说一些“不起作用”是没有用的。这可能意味着任何事情。您尝试调用 Close() (在什么对象上?)它“不起作用”:它是否引发了异常?编译器是否告诉你它不是你试图调用它的神秘秘密未知对象的成员?要不然是啥?事情可能以多种方式“不起作用”。说哪个。
  • 不工作意味着什么都没有发生
  • 你的 CommandHandler 类是如何实现的?
  • 这对你来说可能也很有趣:stackoverflow.com/questions/419596/…

标签: c# wpf mvvm


【解决方案1】:

您可以设计您的窗口以接收用于表示关闭请求的上下文对象

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();
    }
}

【讨论】:

  • 我确信有更简单的解决方案
  • @mike_pl 你想将你的代码从你的 UI 中分离出来,这样它们就不会互相认识(MVVM)......这是一个非常好的解决方案......
  • 为什么 public MainWindow(ICloseable context) { InitializeComponent(); context.CloseRequest += (s, e) => this.Close();它没有非参数构造函数??现在我不能在其他地方创建这个窗口,我应该用什么来创建那个主窗口?
  • bitbucket.org/michal_be/firstwpf/src/… 这是我的代码,如果可以的话,请让它工作:/
  • 现在我无法在其他地方创建 MainWindow() 的这个对象,因为我不知道将什么作为参数传递给它的构造函数...
猜你喜欢
  • 2016-09-04
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多