当我单击MenuItem时,命令工作正常,但当我点击键绑定时,它永远不会被调用。有什么想法吗?
XAML:
<Page.InputBindings>
<KeyBinding Key="N"
Modifiers="Control"
Command="{Binding Path=MenuCommands:NewProject}"/>
</Page.InputBindings>
<MenuItem x:Name="NewProjectMenuItem"
Header="New Project"
Click="NewProjectMenuItem_Click"
InputGestureText="Ctrl+N"/>
C#(XAML来源):
private void NewProjectMenuItem_Click(object sender, RoutedEventArgs e)
{
MenuCommands.NewProject.Execute(NewProjectMenuItem);
}
注意:我绑定到页面中的输入,如果不对程序进行一些重大更改,我无法在窗口中绑定它。
谢谢, 菲利普
答案 0 :(得分:0)
我认为您需要将CanExecute事件设置为true。
XAML:
<Window.InputBindings>
<KeyBinding Key="B"
Modifiers="Control"
Command="ApplicationCommands.Open" />
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Open" CanExecute="CommonCommandBinding_CanExecute" Executed="OpenCommand_Executed" />
</Window.CommandBindings>
<Button Command="Open" ToolTip="Open">
<Image Source="/WPFeBookProject;component/Resources/Images/Open-icon.png" />
</Button>
代码背后:
private void CommonCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Open executed has been triggered!");
}
答案 1 :(得分:0)
在WPF中,InputGestureText不是真正的绑定。这只是一个视觉提示。您必须在Window_PreviewKeyDown中对键绑定进行编码。
KeyBinding可以被某些控件捕获,因此最好避免使用它。
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control)
{
switch (e.Key)
{
case Key.N:
MenuCommands.NewProject.Execute(NewProjectMenuItem);
break;
}
}
}