首页 > 解决方案 > 使用 MVVM 复制窗口关闭事件

问题描述

我想在关闭窗口时使用两个事件。

  1. 用户 [退出] 按钮
  2. 窗口标题中的 [X] 按钮

我做了一个用户退出按钮。

<Button Context="Exit" Command="{Binding OnClickExitCommand}" <BR> CommandParameter={Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" />

我还在窗口标题上创建了一个 X 按钮事件。

<i:Interaction.Triggers> <BR>
  <i:EventTrigger EventName="Closing"> <BR>
     <cmd:EventToCommand Command="{Binding OnClickExitCommand}" PassEventArgsToCommand="True"/> <BR>
  </i:EventTrigger> <BR>
</i:Interaction.Triggers>

OnClickExitCommand一起使用,但使用 if 语句分隔。

private void OnClickExitCommand(object e)
{
    if (e is System.Windows.Window window)
    {
        if (System.Windows.MessageBox.Show($"Button Close.", "Close1", System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
        {
            window.Close();
        }
    }
    else if (e is System.ComponentModel.CancelEventArgs cancel)
    {
        if (System.Windows.MessageBox.Show($"Window Title Close.", "Close2", System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
        {
            cancel.Cancel = false;
        }
        else
        {
            cancel.Cancel = true;
        }
    }
}

但是这里出现了一个问题。

如果Window.Close()在按下按钮时触发,则关闭事件再次发生并工作两次。(按钮关闭显示消息 -> 窗口标题关闭显示消息)

有没有办法避免这种情况?

标签: c#eventsmvvmcommandwindow

解决方案


推荐阅读