c# - 值不能为空 CommandBinding 自定义命令

标签 c# wpf

我几天前才开始使用 WPF,遇到了一个我不明白的问题。

我收到以下错误:

Value cannot be null. Parametername: value

错误发生在这里:

<Window.CommandBindings>
        <CommandBinding Command="self:CustomCommands.Exit" Executed="ExitCommand_Executed" CanExecute="ExitCommand_CanExecute"/>
</Window.CommandBindings>

我当然在 xaml 中设置了命名空间 xmlns:self="clr-namespace:PrintMonitor"

代码隐藏:

namespace PrintMonitor
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ExitCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if(e != null)
                e.CanExecute = true;
        }

        private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }

    public static class CustomCommands
    {
        public static readonly RoutedUICommand Exit = new RoutedUICommand
                (
                        "Beenden",
                        "Exit",
                        typeof(CustomCommands),
                        new InputGestureCollection()
                        {
                            new KeyGesture(Key.F4, ModifierKeys.Alt)
                        }
                );
    }
}

那么为什么如果我使用自定义命令会出现此错误,而如果我使用例如Command="ApplicationCommands.New" 以及如何修复此错误?

代码是 this tutorial 的一部分.

最佳答案

单击设计器窗口下方的“启用项目代码”按钮

Enable Project Code button

关于c# - 值不能为空 CommandBinding 自定义命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35035195/

相关文章:

wpf - 在 xaml 中访问属性背后的代码

wpf - 如何使用数据绑定(bind)在 WPF 中设置列​​ TableView 项的背景颜色?

c# - 内联创建和使用一次性对象是否安全?

c# - HTTPServerUtility.Transfer 是否比 Response.Redirect 在 asp.net 网站性能方面更有用?

c# - 将逗号分隔的参数传递给 SQL 中的存储过程

wpf - 如何将 View 拆分为 m-v-vm 中的模块

wpf - 如何以编程方式设置网格行和列位置

c# - GetMethod 返回 null

c# - 如何使用 Xamarin.Forms 将导航按钮添加到主详细信息页面的标题

c# - 在 wpf 应用程序中初始化功能区控件时出错