c# - 使用 MVVM 复制窗口关闭事件
问题描述
我想在关闭窗口时使用两个事件。
- 用户 [退出] 按钮
- 窗口标题中的 [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()
在按下按钮时触发,则关闭事件再次发生并工作两次。(按钮关闭显示消息 -> 窗口标题关闭显示消息)
有没有办法避免这种情况?
解决方案
推荐阅读
- javascript - 如何在 div 中获取 div 或图像的位置(顶部和左侧位置)并在 CSS 中使用这些值?
- swift - Appdelegate sigabrt 没有出现任何东西!在主故事板中
- neo4j - 浏览 Neo4j 中的列表
- java - Spring boot 1.x,如何将指标增加一个数量
- swift - 使用 swift 在 macOS 中打开新的伪终端设备文件
- git - 删除 git 历史记录中的多合并功能分支
- django - 如何在 django 中保存数组数据?
- php - 使用 PHP 和 mysql 创建 CSV 文件
- javascript - 具有多个返回值的 Ajax 调用服务
- datetime - 在 java 8 中解析时间字符串 - ClockHourOfAmPm 的值无效