我刚刚开始使用WPF,并且遇到了一个我不明白的问题.
我收到以下错误:
值不能为空.Parametername:值
这里发生错误:
<Window.CommandBindings>
<CommandBinding Command="self:CustomCommands.Exit" Executed="ExitCommand_Executed" CanExecute="ExitCommand_CanExecute"/>
</Window.CommandBindings>
Run Code Online (Sandbox Code Playgroud)
我当然xmlns:self="clr-namespace:PrintMonitor"在xaml中设置了命名空间.
代码隐藏:
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)
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
那么,如果我使用自定义命令,为什么会出现此错误,但如果我使用自动命令,则会出现此问题Command="ApplicationCommands.New",如何修复此错误?
该代码是本教程的一部分.
也许您需要将 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();
}
}
Run Code Online (Sandbox Code Playgroud)