WPF自定义命令在上下文菜单中禁用,直到单击任何按钮 [英] WPF custom command in context menu are disabled until any button clicked
问题描述
我有一个自定义命令,我尝试从上下文菜单执行它们,但它们总是显示为禁用,除非我单击任何按钮的UI(按钮没有任何与命令有关)。
I have a custom command and I try to execute them from the context menu, but they are always displayed as disabled unless I click any button on the UI (buttons do not have anything to do with commands).
单击按钮后,命令开始正确显示(如果不可用,则会禁用并启用命令)。
After clicking a button, commands start to be displayed correctly (when they are unavailable they get disabled and enabled if available).
编辑:原来是不是按钮点击使命令正常工作,但按钮或其他控件焦点(例如,如果我选项卡到控件,这也启用我的命令)。
it turns out that it is not the button click which makes command work correctly, but button or other controls in focus (e.g. if I tab into a control this also enables my commands).
下面是命令的代码:
<Window.InputBindings>
<KeyBinding Command="{x:Static local:MainWindow.Quit}" Key="Q" Modifiers="Ctrl"/>
<KeyBinding Command="{x:Static local:MainWindow.Disconnect}" Key="D" Modifiers="Ctrl"/>
</Window.InputBindings>
<Window.ContextMenu>
<ContextMenu Opacity="95">
<MenuItem Header="Quit Application Ctrl + Q" Command="{x:Static local:MainWindow.Quit}"/>
<MenuItem Header="Disconnect from the pump Ctrl + D" Command="{x:Static local:MainWindow.Disconnect}"/>
</ContextMenu>
</Window.ContextMenu>
这里是命令CanExecuteMethod:
Here is the commands CanExecuteMethod:
public static RoutedCommand Quit = new RoutedCommand();
private void QuitCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
e.Handled = true;
}
推荐答案
确实有一些特殊的上下文菜单作为命令的载体:
菜单不被视为窗口的一部分,因此不像它的视觉树中的一个元素。
Completely different track, now: there is indeed something special about the ContextMenu as the carrier for commands: the menu is not regarded as part of the window and therefore does not behave like an element in its visual tree would.
这里定义的问题有不同的解决方案:
http:// www .wpftutorial.net / RoutedCommandsInContextMenu.html
There are different solutions for your problems defined here: http://www.wpftutorial.net/RoutedCommandsInContextMenu.html
最简单的方法似乎是添加到您的XAML(窗口):
The easiest approach seems to be adding this to your XAML (for the window):
FocusManager.FocusedElement="{Binding RelativeSource={x:Static RelativeSource.Self}, Mode=OneTime}"
这篇关于WPF自定义命令在上下文菜单中禁用,直到单击任何按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!