2016-03-15 63 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; 
      } 
     } 
    } 
} 
相關問題