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;
}
}
您的視圖模型構造函數初始化你的命令,你可以有一個'私人設置' – XAMlMAX
@XAMlMAX:當你第一次嘗試訪問它時(懶惰初始化)(在'get'中) –
我有類似的問題,一旦我初始化它我的構造函數一切都開始工作。 – XAMlMAX