WPF命令问题
为什么命令控制总是被禁用,但命令可以执行?命令还可以使用 Alt + F4
运行
public static class CommandLibrary {
static CommandLibrary() {
ShutDownCommand = new RoutedUICommand("Exit", "Exit", typeof(CommandLibrary), new InputGestureCollection {new KeyGesture(Key.F4, ModifierKeys.Alt)});
}
public static RoutedUICommand ShutDownCommand { get; private set; }
public static void BindCommands(Window hostWindow) {
if (hostWindow == null)
return;
hostWindow.CommandBindings.Add(new CommandBinding(ShutDownCommand, OnShutDownCommandExecuted, OnShutDownCommandCanExecute));
}
private static void OnShutDownCommandExecuted(object sender, ExecutedRoutedEventArgs e) {
MessageBox.Show("ShutDown Excuted!");
}
private static void OnShutDownCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}
}
<MenuItem Command="local:CommandLibrary.ShutDownCommand" />
Why commanded control is always disabled however command can be executed? Command also runs with Alt + F4
public static class CommandLibrary {
static CommandLibrary() {
ShutDownCommand = new RoutedUICommand("Exit", "Exit", typeof(CommandLibrary), new InputGestureCollection {new KeyGesture(Key.F4, ModifierKeys.Alt)});
}
public static RoutedUICommand ShutDownCommand { get; private set; }
public static void BindCommands(Window hostWindow) {
if (hostWindow == null)
return;
hostWindow.CommandBindings.Add(new CommandBinding(ShutDownCommand, OnShutDownCommandExecuted, OnShutDownCommandCanExecute));
}
private static void OnShutDownCommandExecuted(object sender, ExecutedRoutedEventArgs e) {
MessageBox.Show("ShutDown Excuted!");
}
private static void OnShutDownCommandCanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}
}
<MenuItem Command="local:CommandLibrary.ShutDownCommand" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常发生这种情况是因为在设置了 Command 的控件范围内没有该命令的 CommandBinding。如果您在 CanExecute 处理程序中设置断点,MenuItem 是否会命中该断点?
Usually this happens because there's no CommandBinding for the command in the scope of the control which has the Command set on it. If you set a breakpoint in the CanExecute handler does it get hit for the MenuItem?