值不能为null CommandBinding自定义命令

时间:2016-01-27 10:47:19

标签: c# wpf

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

我收到以下错误:

  

值不能为空。参数名称:值

此处发生错误:

<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的一部分。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

也许您需要将CustomCommands设置为非静态,

让MainWindow的DataContext成为CustomCommands

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

public partial class MainWindow : Window
{
    public  CustomCommands CM;
    public MainWindow()
    {
        CM = new  CustomCommands();
        this.DataContext = CM;
        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();
    }

}

答案 2 :(得分:0)

我遇到了这个问题,然后我清理了一下,然后构建了解决方案,结果就消失了。作为将来的参考,我发现使用Visual Studio的WPF的许多问题只是先清理后再构建,不知道为什么这些问题在WPF + VS中会更频繁地发生。