2016-03-15 64 views
1

我使用稍微改编的RelayCommand将命令引导到我的视图模型,这工作正常,但出于某种原因,我无法获得输入绑定工作。例如,我有这样的菜单:KeyBinding不与RelayCommand一起工作

<Grid DataContext="{StaticResource app}"> 
... 
    <MenuItem Header="_Run" IsEnabled="{Binding HasScript}"> 
     <MenuItem Header="_Run" Command="{ Binding RunCommand }" Style="{StaticResource menuEnabledStyle}" InputGestureText="F5"/> 
     ... 
    </MenuItem> 
</Grid> 

当您单击菜单项(显然)这个运行良好,但我这里定义的快捷键:

<Window.InputBindings> 
    <KeyBinding Key="F5" 
       Command="{Binding RunCommand}"/> 
    <KeyBinding Modifiers="Alt" Key="F4" 
       Command="ApplicationCommands.Close"/> 
</Window.InputBindings> 

但按F5什么都不做(仅供参考,对ApplicationCommands.Close的约束效果很好)。没有绑定错误(如果我将其更改为绑定不存在的FooCommand,我立即得到一个绑定错误),我无法弄清楚它在这里丢失了什么。

我命令我的视图模型定义如下:

private RelayCommand _runCommand; 
public ICommand RunCommand 
{ 
    get 
    { 
     if (_runCommand == null) 
     { 
      _runCommand = new RelayCommand(p => { this.CurrentScript.Run(); }, p => this.CurrentScript != null && !this.CurrentScript.IsRunning); 
     } 
     return _runCommand; 
    } 
} 
+0

您的视图模型构造函数初始化你的命令,你可以有一个'私人设置' – XAMlMAX

+0

@XAMlMAX:当你第一次尝试访问它时(懒惰初始化)(在'get'中) –

+0

我有类似的问题,一旦我初始化它我的构造函数一切都开始工作。 – XAMlMAX

回答

2

命令的绑定不具有数据上下文(当然,它使用了窗户,但没有设置)。所以,你必须指定它。

下面是完整的,工作测试用例我做:

XAML:

<Window x:Class="WpfApplication30.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:WpfApplication30" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <local:VM x:Key="app" /> 
    </Window.Resources> 
    <Window.InputBindings> 
     <KeyBinding Key="F5" Command="{Binding RunCommand, Source={StaticResource app}}" /> 
    </Window.InputBindings> 
    <Grid DataContext="{StaticResource app}"> 
     <Menu> 
      <MenuItem Header="_File"> 
       <MenuItem Header="_Run" Command="{Binding RunCommand}" InputGestureText="F5" /> 
      </MenuItem> 
     </Menu> 
    </Grid> 
</Window> 

CS:

using System.Windows; 
using Microsoft.TeamFoundation.MVVM; 

namespace WpfApplication30 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 
    } 

    public class VM 
    { 
     private RelayCommand _runCommand; 
     public RelayCommand RunCommand 
     { 
      get 
      { 
       if (_runCommand == null) 
       { 
        _runCommand = new RelayCommand(p => { MessageBox.Show("RunCommand"); }); 
       } 
       return _runCommand; 
      } 
     } 
    } 
} 
相关问题