C# 在WPF/MVVM中按右上角的关闭图标时如何处理关闭窗口?
我可以用C# 在WPF/MVVM中按右上角的关闭图标时如何处理关闭窗口?,c#,wpf,mvvm,event-handling,C#,Wpf,Mvvm,Event Handling,我可以用ICommand绑定按钮和菜单项并关闭窗口。 它与本教程中描述的完全一样-通过XAML中可访问的命令属性 但教程中没有描述或实现如何通过按窗口右上角的标准“关闭”图标来关闭。我需要在我的应用程序中执行一些清理。 我的问题是如何将命令绑定到关闭事件,以便在用户按下关闭图标(不是按钮或菜单项-我知道如何管理此类情况)时执行该命令 如何处理这一点以避免违反MVVM方法? 谢谢 我会将命令绑定到应用程序的退出事件 我喜欢使用为将命令绑定到事件而发现的AttachedCommand行为,尽管我知道
ICommand
绑定按钮和菜单项并关闭窗口。
它与本教程中描述的完全一样-通过XAML中可访问的命令属性
但教程中没有描述或实现如何通过按窗口右上角的标准“关闭”图标来关闭。我需要在我的应用程序中执行一些清理。
我的问题是如何将命令
绑定到关闭事件,以便在用户按下关闭图标(不是按钮或菜单项-我知道如何管理此类情况)时执行该命令
如何处理这一点以避免违反MVVM方法?
谢谢 我会将命令绑定到应用程序的退出事件
我喜欢使用为将命令绑定到事件而发现的AttachedCommand
行为,尽管我知道您也可以使用Blend的交互触发器完成同样的事情。我会将命令绑定到应用程序的退出事件
我喜欢使用为将命令绑定到事件而发现的AttachedCommand
行为,尽管我知道您也可以使用Blend的交互触发器来完成同样的事情。包含一个名为EventToCommand的行为,它为您提供了将命令绑定到事件的简单方法
下面的XAML代码片段显示了如何在引发窗口的Closed事件时执行名为“CloseCommand”的命令的示例:
<Window x:Class="EventToCommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
Title="MainWindow" Height="300" Width="500">
<!-- Make sure to put this tag directly inside the Window,
and not inside a child element, since it is the Windows that has the Closed event -->
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closed">
<cmd:EventToCommand Command="{Binding CloseCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<!-- Windows contents -->
</Window>
要访问EventToCommand行为,您需要从下载MVVM Light Toolkit,然后参考以下DLL:
- GalaSoft.MvvmLight.dll
- GalaSoft.MvvmLight.Extras.dll
- System.Windows.Interactivity.dll
这就是所需要的一切
有关如何开始使用该工具包的更多说明,请参见。包含一个名为EventToCommand的行为,它为您提供了将命令绑定到事件的简单方法
下面的XAML代码片段显示了如何在引发窗口的Closed事件时执行名为“CloseCommand”的命令的示例:
<Window x:Class="EventToCommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
Title="MainWindow" Height="300" Width="500">
<!-- Make sure to put this tag directly inside the Window,
and not inside a child element, since it is the Windows that has the Closed event -->
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closed">
<cmd:EventToCommand Command="{Binding CloseCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<!-- Windows contents -->
</Window>
要访问EventToCommand行为,您需要从下载MVVM Light Toolkit,然后参考以下DLL:
- GalaSoft.MvvmLight.dll
- GalaSoft.MvvmLight.Extras.dll
- System.Windows.Interactivity.dll
这就是所需要的一切
有关如何开始使用该工具包的更多说明,请参见。谢谢Erik。我现在知道的主要问题是,如果没有微软的领导,没有简单的解决方案。。。像往常一样。。。谢谢你澄清问题:)谢谢Erik。我现在知道的主要问题是,如果没有微软的领导,没有简单的解决方案。。。像往常一样。。。感谢您对问题的澄清:)