You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XAML中使用WPF的SystemCommands.CloseWindow命令

问题原因
  • SystemCommands类不属于WPF XAML默认引用的命名空间,直接在XAML中写SystemCommands.CloseWindow时,解析器无法定位到对应的类成员,所以会报不可访问的错误。
  • ApplicationCommands属于WPF默认内置的路由命令集合,默认就在XAML的标准命名空间下,所以可以直接使用。
解决步骤
  1. 首先在你的XAML文件的Window根节点中添加System.Windows.Shell命名空间的映射,示例如下:
<Window x:Class="你的项目命名空间.你的窗口类名"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        <!-- 新增下面这行命名空间映射,前缀shell可以自定义,只要后续对应即可 -->
        xmlns:shell="clr-namespace:System.Windows.Shell;assembly=PresentationFramework"
        Title="主窗口" Height="450" Width="800">
  1. 修改你的CommandBinding写法,加上刚才定义的命名空间前缀:
<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.New" CanExecute="NewCommandCanExecute" Executed="NewCommandExecuted"/>
    <CommandBinding Command="ApplicationCommands.Open" CanExecute="OpenCommandCanExecute" Executed="OpenCommandExecuted"/>
    <CommandBinding Command="ApplicationCommands.Save" CanExecute="SaveCommandCanExecute" Executed="SaveCommandExecuted"/>
    <!-- 加上shell前缀,对应刚才的命名空间映射 -->
    <CommandBinding Command="shell:SystemCommands.CloseWindow" CanExecute="CloseWindowCanExecute" Executed="CloseWindowExecuted"/>
</Window.CommandBindings>
  1. 若使用的是.NET Framework 4.0及更早版本,需要先安装Microsoft.Windows.Shell的NuGet包,再进行上述配置;.NET Framework 4.5+、.NET Core 3.0+、.NET 5+均已内置该类,无需额外安装包。

内容的提问来源于stack exchange,提问作者digitig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:36:04