如何在 MVVM WPF 应用程序中取消窗口关闭

2023-12-23

单击“取消”按钮(或右上角的 X,或 Esc)后如何取消从特定表单退出?

WPF:

<Window
  ...
  x:Class="MyApp.MyView"
  ...
/>
  <Button Content="Cancel" Command="{Binding CancelCommand}" IsCancel="True"/>
</Window>

视图模型:

public class MyViewModel : Screen {
  private CancelCommand cancelCommand;
  public CancelCommand CancelCommand {
    get { return cancelCommand; }
  }
  public MyViewModel() {
    cancelCommand = new CancelCommand(this);
  }
}

public class CancelCommand : ICommand {

  public CancelCommand(MyViewModel viewModel) {
    this.viewModel = viewModel;
  }

  public override void Execute(object parameter) {
    if (true) { // here is a real condition
      MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show(
        "Really close?",  "Warning", 
        System.Windows.MessageBoxButton.YesNo);
      if (messageBoxResult == MessageBoxResult.No) { return; }
    }
    viewModel.TryClose(false);
  }

  public override bool CanExecute(object parameter) {
    return true;
  }
}

当前代码不起作用。如果用户在弹出对话框中选择“否”,我希望用户保留当前表单。 此外,重写 CanExecute 也没有帮助。它只是禁用该按钮。我想允许用户点击按钮,但随后通知他/她,数据将丢失。 也许我应该在按钮上分配一个事件侦听器?

EDIT:

我设法在“取消”按钮上显示弹出窗口。但我仍然无法管理 Esc 或 X 按钮(右上角)。看来我对取消按钮感到困惑,因为当我单击 X 按钮或 Esc 时会执行 Execute 方法。

EDIT2:

我改变了问题。这是“如何取消取消按钮”。然而,这不是我想要的。我需要取消 Esc 或 X 按钮。 在“MyViewModel”中我添加:

        protected override void OnViewAttached(object view, object context) {
            base.OnViewAttached(view, context);
            (view as MyView).Closing += MyViewModel_Closing;
        }

        void MyViewModel_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
            if (true) {
                MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show(
                  "Really close?",  "Warning", 
                  System.Windows.MessageBoxButton.YesNo);
                if (messageBoxResult == MessageBoxResult.No) {
                    e.Cancel = true;
                }
            }
        }

这解决了我的问题。但是,我需要 ICommand 来了解单击了哪个按钮,“保存”或“取消”。有什么办法可以消除事件的使用吗?


您正在尝试在 ViewModel 类中完成 View 的工作。让您的 View 类处理关闭请求以及是否应该取消它。

要取消关闭窗口,您可以订阅Closing查看和设置事件CancelEventArgs.Cancel显示后为 trueMessageBox.

这是一个例子:

<Window
    ...
    x:Class="MyApp.MyView"
    Closing="OnClosing"
    ...
/>
</Window>

背后代码:

private void OnClosing(object sender, CancelEventArgs e)
{
    var result = MessageBox.Show("Really close?",  "Warning", MessageBoxButton.YesNo);
    if (result != MessageBoxResult.Yes)
    {
        e.Cancel = true;
    }

    // OR, if triggering dialog via view-model:

    bool shouldClose = ((MyViewModel) DataContext).TryClose();
    if(!shouldClose)
    {
        e.Cancel = true;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MVVM WPF 应用程序中取消窗口关闭 的相关文章

随机推荐